Skip to content

Instantly share code, notes, and snippets.

@shagohead
Last active December 17, 2019 06:55
Show Gist options
  • Save shagohead/f54e861e6eda55404c614c56edfa3e8b to your computer and use it in GitHub Desktop.
Save shagohead/f54e861e6eda55404c614c56edfa3e8b to your computer and use it in GitHub Desktop.
environment variables helper script
#!/usr/bin/env bash
# Usage:
# --- .env file creation mode (will be created from provided files):
# env.sh f .env.dist .another.env.dist
# --- command mode (will be run with exported variables):
# env.sh c subcommand
if [[ $1 == "f" ]]; then
if [[ -z "$2" ]]; then
echo -e "\033[31mProvide at least one .env.dist file name\033[0m"
exit 1
fi
variables=()
for arg in "${@:2}"; do
if [[ ! -f "$arg" ]]; then
echo -e "\033[2mThere is no file named $arg\033[0m"
continue
fi
while IFS= read -r line; do
if [[ ! "$line" =~ ^[a-zA-Z_0-9]+=.* ]]; then
continue
fi
line_var=($(echo $line | tr "=" "\n"))
var_found=0
for var in "${variables[@]}"; do
if [[ $var == "${line_var[0]}" ]]; then
var_found=1
fi
done
if [[ "$var_found" == "0" ]]; then
variables+=(${line_var[0]})
fi
declare "variable_${line_var[0]}=${line_var[1]}"
done < $arg
done
IFS=$'\n' sorted=($(sort <<<"${variables[*]}")); unset IFS
> .env
for var in "${sorted[@]}"; do
name="variable_${var}"
echo "${var}=${!name}" >> .env
done
elif [[ $1 == "c" ]]; then
if [[ ! -f ".env" ]]; then
echo -e "\033[31mThere is no .env file\033[0m"
exit 1
fi
export $(cat .env) && ${@:2}
else
echo -e "\033[31mProvide mode name (f | c)\033[0m"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment