I am trying to implement a migration script to export some environment variables in bash.
It is more difficult to be explained that to implement.
Basically, there is a set of environment variables and a set of their default values.
A small fragment of the (gigantic) migration script is reported below:
REQUIRED_ENVIRONMENT_VARIABLES=( "BAR" "FOO" "BAZ" )
ENVIRONMENT_VARIABLES_DAFAULT_VALUES=( "/some/path" "0" "true" )
for i in "${!REQUIRED_ENVIRONMENT_VARIABLES[@]}"; do
echo "checking environment variable [$i] ${REQUIRED_ENVIRONMENT_VARIABLES[$i]} which default value is: [${ENVIRONMENT_VARIABLES_DAFAULT_VALUES[$i]}]"
if [[ -z "${REQUIRED_ENVIRONMENT_VARIABLES[$i]}" ]]; then
echo "variable ${REQUIRED_ENVIRONMENT_VARIABLES[$i]} exported with value ${ENVIRONMENT_VARIABLES_DAFAULT_VALUES[$i]}"
echo "export ${REQUIRED_ENVIRONMENT_VARIABLES[$i]}"="${ENVIRONMENT_VARIABLES_DAFAULT_VALUES[$i]}" >> $HOME/.bash_profile
fi
done
Simply, the for loop iterates for each variable into REQUIRED_ENVIRONMENT_VARIABLES
:
- if the var exists and has some value, skip it and continue to the next iteration;
- if the var doesn't exist, create a new entry
export VAR_NAME=DEFAULT_VALUE
into the .bash_profile
So, for example, if the original contents of .bash_profile is:
(.bash_profile)
export FOO=1
export ASD=https://cool.url/
...
after running the migration script, the result should be:
(.bash_profile)
export FOO=1
export ASD=https://cool.url/
...
export BAR=/some/path
export BAZ=true
FOO
remains untouched because already exists.
The problem with this code is that I see no new entries when I try to append it to the .bash_profile using the echo
command. Why?