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.

Pavol Kutaj

--

${<parameter>-word} 
${<parameter>:-word}
  • ${<parameter>-word} expands to word if <parameter> is unset or null, but not if declared
  • declared variables are untouched.
  • ${<parameter>:-word} expands to word 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

LINKS

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com