Skip to content

Instantly share code, notes, and snippets.

@brysem
Created March 22, 2022 10:05
Embed
What would you like to do?
.env Switcher
#!/bin/bash
# Creator: Bryse Meijer
# Scans which .env files are available in your folder and renames them appropriately.
# Required: Add a new line to the top of your .env with the name of your environment "# Production" to indicate what kind of environment it is.
# Example (.env): # Test
env_choice="${1}"
file_env() {
head -n 1 $1 2> /dev/null | tr -d '[:space:]' | cut -c2- | tr '[:upper:]' '[:lower:]'
}
file_exists() [[ -f "./$file" ]];
env_current=""
env_array=("local" "test" "acceptance" "production")
available_array=()
for i in ${env_array[*]}; do
file=".env.$i"
if file_exists $file; then
available_array+=("$i")
fi
done
if file_exists ".env"; then
environment=$(file_env ".env")
if [[ " ${env_array[*]} " =~ " ${environment} " ]]; then
available_array+=("$environment")
env_current=$environment
fi
fi
if [ -z "$env_choice" ]; then
echo "Environments available:"
for i in ${available_array[*]}; do
if [ "$i" = "$env_current" ]; then
echo "* $i"
else
echo "- $i"
fi
done
exit
fi
if [[ ! " ${available_array[*]} " =~ " ${env_choice} " ]]; then
echo "The chosen environment $env_choice is not available."
exit
fi
if [ "$env_choice" = "$env_current" ]; then
echo "You are currently already using environment $env_choice."
exit
fi
# for i in ${available_array[*]}; do
# echo $i
# done
# echo "Current Environment: $env_current"
# echo "Chosen Environment: $env_choice"
mv .env ".env.$env_current"
mv ".env.$env_choice" .env
echo "Environment switched to $env_choice from $env_current"
@brysem
Copy link
Author

brysem commented Mar 22, 2022

Install

curl -L https://gist.githubusercontent.com/brysem/d94c5c8ad04d8259bb104a23151886d1/raw/44c1ebc0305325e15b69877a21d103add91430ff/senv > /usr/local/bin/senv
chmod +x /usr/local/bin/senv

Setup

Don't forget to add a hashtag as the first line of each of your .env files with the name of the environment.
image

Usage

List available environments. The current environment is marked with an asterik.

senv

Switch environment

senv local

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