I'm trying to understand a Bash script. I stumbled upon this:
DIR=${1:-"/tmp"}
What does that mean?
I'm trying to understand a Bash script. I stumbled upon this:
DIR=${1:-"/tmp"}
What does that mean?
 
    
     
    
    :- is actually an operator it says that if $1 (first argument to the script) is not set or is null then use /tmp as the value of $DIR and if it's set assign it's value to $DIR.
DIR=${1:-"/tmp"}
is short for
if [ -z $1 ]; then
        DIR='/tmp'
else
        DIR="$1"
fi
It can be used with any variables not just positional parameters:
$ echo ${HOME:-/tmp} # since $HOME is set it will be displayed.
/home/codaddict
$ unset HOME   # unset $HOME.
$ echo ${HOME:-/tmp} # since $HOME is not set, /tmp will be displayed.
/tmp
$ 
 
    
    That syntax is parameter expansion:
${parameter:-word}If
parameteris unset or null, the expansion ofwordis substituted. Otherwise, the value ofparameteris substituted.
So if $1 is unset or null, it evaluates to "/tmp" and to the value of $1 otherwise.