PythonIntermediate · Windows, macOS, or Linux; Python 3.12+

Compare environment-file names

Compare declared environment-variable names with a template and detect duplicates without printing values.

Before you begin

  • Python 3.12 or later.
  • Read access to the selected inputs.
What this script changesRead-only local report. No permissions, accounts, configuration, or input files are changed. Review filenames and metadata before sharing.

Set up your example

  1. Save as security-dotenv-contract.py.
  2. Open a terminal in its folder.
  3. Run python "security-dotenv-contract.py" --help and prepare the listed input files.

Sample files in this download:

  • .env.example
  • .env

Download the ZIP, extract it, and open a terminal inside the extracted folder. The source file is security-dotenv-contract.py.

Run the script

Run command
python "security-dotenv-contract.py" ".env.example" ".env"

If your system uses python3 instead of python, use that command for Python examples. Keep paths containing spaces in quotes. Required inputs and optional settings are described in the code and setup steps.

What to expect

A missing DATABASE_URL appears by name; no values are displayed.

The complete script

security-dotenv-contract.py
#!/usr/bin/env python3
"""Compare declared environment-variable names with a template and detect duplicates without printing values."""
import argparse
import sys
import json
from pathlib import Path
import re
from collections import Counter

def main():
    parser = argparse.ArgumentParser(description='Compare declared environment-variable names with a template and detect duplicates without printing values.')
    parser.add_argument('template',type=Path)
    parser.add_argument('actual',type=Path)
    args = parser.parse_args()
    def keys(path):
        result=[]
        for line in path.read_text(encoding='utf-8-sig').splitlines():
            line=line.strip()
            if line.startswith('export '):line=line[7:]
            if not line or line.startswith('#') or '=' not in line:continue
            name=line.split('=',1)[0].strip()
            if re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*',name):result.append(name)
        return result
    expected=keys(args.template);actual=keys(args.actual)
    print(json.dumps({'missing':sorted(set(expected)-set(actual)),'extra':sorted(set(actual)-set(expected)),'duplicate_names':sorted(k for k,v in Counter(actual).items() if v>1)},indent=2))

if __name__ == '__main__':
    try:
        main()
    except (OSError, ValueError, RuntimeError) as exc:
        print(f'Error: {exc}', file=sys.stderr)
        sys.exit(1)

Open source as plain text · Download source and sample files

How it works

  1. Compare declared environment-variable names with a template and detect duplicates without printing values.
  2. Arguments are explicit and expected input errors produce a message with a nonzero exit code.
  3. Results reflect your selected local data or the specific endpoint you choose; the example illustrates the result shape.

Make it your own

Adapt the task

Supply your template and local file. This parser supports simple NAME=value declarations, not complete shell syntax.

Adjust presentation

Edit final print statements or json.dumps indentation to adjust the report layout. Keep input validation and exclusive-create file modes intact.

Change one setting at a time, run it again on sample data, and compare the output. The customization guide walks through this process.

If something goes wrong

An input or dependency is unavailable.

Check the path, quote paths with spaces, and use --help to inspect required arguments.

Actual results differ from the example.

Inputs and system state determine values. Review each finding in context; a report is not proof of system health or a complete security assessment.

Reference & next steps

These official references explain the underlying tools. The Scriptage example and guide are original instructional content. See verification notes for what has been checked and the limits of those checks.

Copies a template for your own notes. It does not send anything.