To set a default value for a variable in a Bash shell script, you can use the ${VARIABLE:-DEFAULT_VALUE}
syntax. This syntax checks if the VARIABLE
is defined and not empty, and if it is not, it will expand to DEFAULT_VALUE
. Otherwise, it will expand to the value of VARIABLE
.
Here is an example of how to use the ${VARIABLE:-DEFAULT_VALUE}
syntax to set a default value for a variable:
# Define the VARIABLE variable with an empty value VARIABLE="" # Set a default value for the VARIABLE variable DEFAULT_VALUE="hello" # Use the ${VARIABLE:-DEFAULT_VALUE} syntax to expand the VARIABLE variable # with the default value if it is not defined or empty echo "${VARIABLE:-DEFAULT_VALUE}"
In this example, the VARIABLE
variable is defined with an empty value. Then, the DEFAULT_VALUE
variable is defined with the string "hello". Finally, the ${VARIABLE:-DEFAULT_VALUE}
syntax is used to expand the VARIABLE
variable, and it will expand to DEFAULT_VALUE
because VARIABLE
is not defined or empty. The echo
command is used to print the expanded value of VARIABLE
, which will be the string "hello".