Skip to content

Instantly share code, notes, and snippets.

@IamNator
Created September 1, 2023 07:02
Show Gist options
  • Save IamNator/232f9ff7be1219e0f55977ccaa59761a to your computer and use it in GitHub Desktop.
Save IamNator/232f9ff7be1219e0f55977ccaa59761a to your computer and use it in GitHub Desktop.
Check ALL ENV in a golang program
#!/bin/bash
# Replace 'application' with the actual path to your Go project directory
PROJECT_DIR="application"
OUTPUT_FILE="env_variables.yaml"
ENV_FILE="$1" # Specify the correct path to your optional environment file
# if $1 is help or -h, print help
if [ "$1" == "help" ] || [ "$1" == "--help" ] || [ "$1" == "-help" ] || [ "$1" == "-h" ] || [ "$1" == "--h" ]; then
echo "Usage: ./check_env.sh [env_file]"
echo " env_file: Optional path to environment file"
exit 0
fi
# if env file is not provided, use .env file
if [ -z "$ENV_FILE" ]; then
ENV_FILE="$PROJECT_DIR/.env"
fi
# Find all Go files in the project directory
GO_FILES=$(find "$PROJECT_DIR" -name "*.go")
# Initialize an array to store unique environment variables
unique_env_vars=()
# Loop through each Go file and find os.Getenv calls
for file in $GO_FILES; do
env_vars=($(grep -oE 'os\.Getenv\("[A-Za-z_][A-Za-z0-9_]*"\)' "$file" | sed -E 's/os\.Getenv\("([A-Za-z_][A-Za-z0-9_]*)"\)/\1/g'))
for env_var in "${env_vars[@]}"; do
if [[ ! " ${unique_env_vars[@]} " =~ " ${env_var} " ]]; then
unique_env_vars+=("$env_var")
fi
done
done
echo "" > "$OUTPUT_FILE"
# Write the unique environment variables to the output file
for env_var in "${unique_env_vars[@]}"; do
echo "$env_var" >> "$OUTPUT_FILE"
done
# Function to check if an environment variable is set
check_env_var() {
if [ -n "$1" ]; then
if [ -n "${!1}" ]; then
echo "true"
elif [ -f "$2" ] && grep -q "^$1=" "$2"; then
echo "true"
else
echo "false"
fi
else
echo "false"
fi
}
# Read the unique environment variables from the file
unique_env_vars=()
while IFS= read -r line; do
unique_env_vars+=("$line")
done < "$OUTPUT_FILE"
# Initialize arrays for true and false variables
true_vars=()
false_vars=()
# Check if environment variables are provided and group them
for env_var in "${unique_env_vars[@]}"; do
if [ -n "$env_var" ]; then
env_var_status=$(check_env_var "$env_var" "$ENV_FILE")
if [ "$env_var_status" == "true" ]; then
true_vars+=("$env_var")
else
false_vars+=("$env_var")
fi
fi
done
> "$OUTPUT_FILE"
# Print true variables at the top, followed by a blank line, then false variables
for env_var in "${true_vars[@]}"; do
echo "$env_var: true" >> "$OUTPUT_FILE"
done
echo >> "$OUTPUT_FILE"
for env_var in "${false_vars[@]}"; do
echo "$env_var: false" >> "$OUTPUT_FILE"
done
echo "--------------------"
echo " Check completed"
echo " Results are written to '$OUTPUT_FILE'"
echo "--------------------"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment