How to Set Default Function Parameter/Variable Values in Bash.
The aim of this pageđź“ť is to explain the setting of default variable values via parameter expansion in bash. There are two forms, with a slight difference of one having an extra colon (':'). Bash is full of small essential illusions, or changes one can easily skip and that make essential difference. Alas.
1 min readApr 15, 2024
${<parameter>-word}
${<parameter>:-word}
${<parameter>-word}
expands toword
if<parameter>
is unset or null, but not if declared- declared variables are untouched.
${<parameter>:-word}
expands toword
if<parameter>
is unset or null or if declared but not defined. Also declared are replaced if undefined.
username0=
echo "username0 has been declared, but is set to null"
echo "using \${username0-\`whoami\`}"
echo "username0 = ${username0-`whoami`}"
# >>> username0 =
echo
echo "username1 has not been declared."
echo "using \${username1-\`whoami\`}"
echo "username1 = ${username1-`whoami`}"
# >>> username1 = admin
echo
username1=
echo "username1 has been declared, but is set to null"
echo "using \${username1:-\`whoami\`}"
echo "username1 = ${username1:-`whoami`}"
# >>> username1 = admin