Last active
April 4, 2024 04:15
-
-
Save tgran2028/9ce608f123384df39958d40db1b799ca to your computer and use it in GitHub Desktop.
Shell command to write environment key/values as JSON to stdout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# | |
# envjson.py | |
""" | |
Dumps alphanumerically sorted environment variables to stdout in JSON format. | |
Usage: | |
./envjson.py # Replace with the actual script name | |
""" | |
import json | |
import os | |
import sys | |
from typing import Literal | |
def main() -> Literal[0, 1]: | |
"""Retrieves environment variables and outputs them as formatted JSON. | |
Args: | |
None | |
Returns: | |
Literal[0, 1]: 0 on success, 1 on error. | |
""" | |
try: | |
# Retrieve environment variables and sort them by their keys | |
environ: dict[str, str] = {k: os.environ[k] for k in sorted(os.environ)} | |
# Output the environment variables as formatted JSON | |
sys.stdout.write(f"{json.dumps(environ, indent=2)}\n") | |
return 0 | |
except Exception as e: | |
# Correctly accessing the exception message | |
sys.stderr.write(f"Error: {str(e)}\n") | |
return 1 | |
if __name__ == "__main__": | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment