Skip to content

Instantly share code, notes, and snippets.

@imerfanahmed
Created April 9, 2025 09:28
Show Gist options
  • Save imerfanahmed/0a4ac265d4c62b2e59aa8ea42a880451 to your computer and use it in GitHub Desktop.
Save imerfanahmed/0a4ac265d4c62b2e59aa8ea42a880451 to your computer and use it in GitHub Desktop.
Update .env Variables for All Apps in a Single Directory with One Command
#!/bin/bash
# Script to add or update environment variables in Laravel .env files
# Usage: ./env_updater.sh [webapps_directory] [env_key] [env_value]
WEBAPPS_DIR=${1:-"webapps"}
ENV_KEY=$2
ENV_VALUE=$3
# Check if required parameters are provided
if [ -z "$ENV_KEY" ] || [ -z "$ENV_VALUE" ]; then
echo "Usage: $0 [webapps_directory] [env_key] [env_value]"
echo "Example: $0 webapps DB_HOST 127.0.0.1"
exit 1
fi
# Check if webapps directory exists
if [ ! -d "$WEBAPPS_DIR" ]; then
echo "Error: Directory '$WEBAPPS_DIR' does not exist."
exit 1
fi
# Find all .env files in the webapps directory and subdirectories
ENV_FILES=$(find "$WEBAPPS_DIR" -name ".env" -type f)
# Check if any .env files were found
if [ -z "$ENV_FILES" ]; then
echo "No .env files found in '$WEBAPPS_DIR' directory."
exit 1
fi
# Function to add or update environment variable
update_env_var() {
local env_file=$1
local key=$2
local value=$3
echo "Processing file: $env_file"
# Check if the key exists in the file
if grep -q "^${key}=" "$env_file"; then
# Update existing key
sed -i "s|^${key}=.*|${key}=${value}|" "$env_file"
echo " Updated: ${key}=${value}"
else
# Add new key-value pair
# Check if file ends with a newline
if [ "$(tail -c 1 "$env_file" | wc -l)" -eq 0 ]; then
# File doesn't end with newline, add one first
echo "" >> "$env_file"
fi
echo "${key}=${value}" >> "$env_file"
echo " Added: ${key}=${value}"
fi
}
# Process each .env file
echo "Found $(echo "$ENV_FILES" | wc -l) .env files"
echo "Updating/Adding: ${ENV_KEY}=${ENV_VALUE}"
echo "------------------------"
for env_file in $ENV_FILES; do
update_env_var "$env_file" "$ENV_KEY" "$ENV_VALUE"
done
echo "------------------------"
echo "Environment variable update complete."
@imerfanahmed
Copy link
Author

Give Permission

chmod +x ./env_updater.sh

Usage:

./env_updater.sh [webapps_directory] [env_key] [env_value]

Example

./env_updater.sh webapps DB_HOST 127.0.0.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment