How to know if a variable has already been defined in Bash?

Asked

Viewed 46 times

1

I have an application that runs from a script sh. I have in this script defined some variables, where I use export to be accessed internally by the application.

However, now I only need to define this variable if it does not exist. I do not get along very well with bash, so I would like to know:

Is there any way to check whether a variable has been set in BASH?

# Se a variável API_BASE_URL não foi definida, cria...
export API_BASE_URL="http://localhost"
  • 1

    Tries: if [ -z "$var" ]; then echo "var is Blank"; Else echo "var is set to '$var'"; fi, where "var" you replace with its variable

1 answer

1


One way to do it is:

export API_BASE_URL=${API_BASE_URL:="http://localhost"}

If the variable already exists, use the current value. Otherwise, use http://localhost. Only that the value is also set if the variable is an empty string. That is:

export API_BASE_URL="a"
export API_BASE_URL=${API_BASE_URL:="http://localhost"}
echo $API_BASE_URL # imprime "a"
export API_BASE_URL=""
export API_BASE_URL=${API_BASE_URL:="http://localhost"}
echo $API_BASE_URL # imprime "http://localhost"
export API_BASE_URL=${API_BASE_URL:="http://localhost"}
echo $API_BASE_URL # imprime "http://localhost"

Another option is to use -z:

[ -z "$API_BASE_URL" ] && export API_BASE_URL="http://localhost"

With the same behavior as the first option (if the variable does not exist or is empty string, the new value is assigned).


But if you do not want to set the value if the variable already exists and is the empty string, switch to:

export API_BASE_URL=${API_BASE_URL="http://localhost"}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.