Skip to content

Instantly share code, notes, and snippets.

@tgran2028
Last active April 4, 2024 04:15
Show Gist options
  • Save tgran2028/9ce608f123384df39958d40db1b799ca to your computer and use it in GitHub Desktop.
Save tgran2028/9ce608f123384df39958d40db1b799ca to your computer and use it in GitHub Desktop.
Shell command to write environment key/values as JSON to stdout
#!/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