1

I`m trying to create environment variables via script if the variable does not exist.

What I am doing for this is the following:

    local env_variable_name="VARIABLE_"$id
    if [[ -z "${env_variable_name}" ]]; then
        break
    else
        local env_var_value=$(generate_value $some_argument)
        export "$env_variable_name"="${env_var_value}"
    fi

My goal is to create an environment variable, for which I can choose my own dynamic name. If the script is fired again, I want to prevent the script to overwrite the value that is initially set.

If I run the script with "source" it works as expected. The environment variable i set and persisted. If I run the script again, the value of the environment variable will be overwritten. The right way is to check if the environment variable exists by its name, but i cant find a way to do this without knowing how the variable name and hardcoding it into the script.

codlix
  • 858
  • 1
  • 8
  • 24
  • 1
    https://stackoverflow.com/questions/3601515/how-to-check-if-a-variable-is-set-in-bash – James Brown Dec 15 '20 at 12:52
  • 1
    Actually in this post this answer https://stackoverflow.com/a/35412000/10781626 was the thing I needed! I´ve already read this post but did not dig deep enough. Thanks! – codlix Dec 15 '20 at 13:04

1 Answers1

0

In regards to this I found the correct solution: https://stackoverflow.com/a/35412000/10781626

The correct code is the following - I needed to change the if statement:

    local env_variable_name="VARIABLE_"$id
    if (declare -p "${env_variable_name}" &>/dev/null); then
        break
    else
        local env_var_value=$(generate_value $some_argument)
        export "$env_variable_name"="${env_var_value}"
    fi

The declare command returns a success if the variable, with the handed name, was already set which leads to the correct call of the if part!

codlix
  • 858
  • 1
  • 8
  • 24