Skip to content

Instantly share code, notes, and snippets.

@yoginsurya
Created August 9, 2025 20:13
Show Gist options
  • Select an option

  • Save yoginsurya/bd66c4ab17288e42e2d4d46ef1476e21 to your computer and use it in GitHub Desktop.

Select an option

Save yoginsurya/bd66c4ab17288e42e2d4d46ef1476e21 to your computer and use it in GitHub Desktop.
Generate .env.sample file based on .env.local or .env file
#!/bin/bash
#
# Generates a .env.sample file from .env.local or .env.
#
# This script creates a sanitized .env.sample file for version control.
# It prioritizes .env.local as the source if it exists, otherwise it uses .env.
# The script preserves comments and empty lines but removes all values from
# key-value pairs, leaving only the keys.
#
# Determine the source file. Prefer .env.local.
if [ -f ".env.local" ]; then
SOURCE_FILE=".env.local"
elif [ -f ".env" ]; then
SOURCE_FILE=".env"
else
# Exit with an error if neither source file is found.
echo "Error: Neither .env.local nor .env file found in the current directory." >&2
exit 1
fi
echo "Using '${SOURCE_FILE}' to generate .env.sample..."
# Define the output file.
OUTPUT_FILE=".env.sample"
# Process the source file to generate the sample file.
#
# The `sed` command operates as follows:
# - It processes the SOURCE_FILE line by line.
# - '/^#/!': This is an address pattern. It selects all lines that DO NOT (!)
# start (^) with a hash (#). This ensures comment lines are ignored.
# - 's/=.*/=/' : This is the substitution command, applied only to the
# lines selected by the address pattern.
# - It finds the first equals sign (=) and all characters that follow (.*)
# on the line.
# - It replaces that entire sequence with a single equals sign (=).
#
# Lines that are empty or do not contain an '=' are unaffected by the substitution
# and are printed as-is. Comment lines are skipped by the address and printed as-is.
# The final output is redirected to the OUTPUT_FILE.
sed '/^#/! s/=.*/=/' "${SOURCE_FILE}" > "${OUTPUT_FILE}"
echo "Successfully created '${OUTPUT_FILE}'."
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment