46 lines
1.2 KiB
Bash
46 lines
1.2 KiB
Bash
#!/bin/bash
|
|
|
|
if [ -z "$1" ] || [ -z "$2" ]; then
|
|
echo "Use: $0 ENV_FILE VARIABLE_NAME (VALUE)"
|
|
exit 1
|
|
fi
|
|
|
|
ENV_FILE=$1
|
|
VARIABLE_NAME=$2
|
|
|
|
# Password gen: 20chars,0-9,a-z
|
|
generate_random_password() {
|
|
#tr -dc 'a-z0-9' </dev/urandom | head -c 20
|
|
pwgen -s 20 1
|
|
}
|
|
|
|
trap 'echo -e "\033[31menv-gen-all.sh: Something went wrong\033[0m"; exit 1' ERR
|
|
set -e
|
|
|
|
export DEBIAN_FRONTEND=noninteractive
|
|
|
|
echo "If the second parameter is specified, use it as the value of the variable..."
|
|
if [ -n "$3" ]; then
|
|
VALUE=$3
|
|
else
|
|
VALUE=$(generate_random_password)
|
|
fi
|
|
|
|
echo "Creating .env file if it doesn't exist..."
|
|
if [ ! -f "$ENV_FILE" ]; then
|
|
echo "# Creating directories if they don't exist..."
|
|
mkdir -p "$(dirname "$ENV_FILE")"
|
|
touch "$ENV_FILE"
|
|
fi
|
|
|
|
echo "Update or add a variable to the .env file"
|
|
if grep -q "^$VARIABLE_NAME=" "$ENV_FILE"; then
|
|
echo "The variable exists, update its value..."
|
|
sed -i "s/^${VARIABLE_NAME//\//\\/}=.*/${VARIABLE_NAME//\//\\/}=${VALUE//\//\\/}/" "$ENV_FILE"
|
|
else
|
|
echo "The variable does not exist, add it to the file..."
|
|
echo "$VARIABLE_NAME=$VALUE" >> "$ENV_FILE"
|
|
fi
|
|
|
|
trap - ERR
|
|
echo "Variable $VARIABLE_NAME successfully updated/added to $ENV_FILE" |