To check if a variable is defined in a shell script, you can use the if [ -z "$VAR" ]
statement. Here, -z
tests if the length of the variable $VAR
is zero or not. If the variable is not defined or has a length of zero, the statement will be true.
To set a default variable value in case the variable is not defined, you can use the ${VAR:-default}
syntax. Here, ${VAR}
returns the value of the variable $VAR
, and :-default
specifies the default value to use if $VAR
is not defined.
Here’s an example script that sets a default value for a variable:
if [ -z "$VAR" ]; then
VAR="default_value"
fi
echo "The value of VAR is: $VAR"
Alternatively, you can use a shorter version of the above script using the ${VAR:=default}
syntax, which sets $VAR
to default
if it is not defined:
echo "The value of VAR is: ${VAR:=default_value}"
In this version, the variable is set to default_value
if it is not defined and then printed.