Set Default Arguments with Bash Shell Parameter Expansions

Share this video with your friends

Send Tweet

In this lesson, we'll see how shell parameter expansions can be used to simply expand a variable's valuable and also provide a default value to a variable, if not set. Note that there are many more possibilities with shell parameter expansions, so check bash's documentation to view them all.

Eliezer Steinbock
Eliezer Steinbock
~ 6 years ago

Why does dir=$1 turn into: dir=${1:-$PWD}. I'm a little confused by the brace ordering. I would have expected something like ${$1 instead of ${1

Cameron Nokes
Cameron Nokes(instructor)
~ 6 years ago

Why does dir=$1 turn into: dir=${1:-$PWD}. I'm a little confused by the brace ordering. I would have expected something like ${$1 instead of ${1

I agree the syntax is strange and I don't think I can give you a satisfactory answer without knowing how the bash interpreter works 🤷‍♂️. Remember that the syntax $var is basically equivalent to ${var}, so syntactically, a variable in bash isn't always preceded by a $. The "why" might be covered here more: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_04.html. Sorry, I couldn't be of more help and that's definitely a good question!