tags:

views:

87

answers:

2

I'm trying to understand a bash script with help of google :)

Then I stumbled upon this:

DIR=${1:-"/tmp"}

What does that mean? Google does not give any relevant result :(

+4  A: 

:- 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
$ 
codaddict
Thanks for making it clear. Stack overflow is too fast :)
First, as Gumbo said in his answer, `:-` accounts not only for unset variable, but also for variable which expands to a null string. Use `-` (without a colon) to test only for set/unset variable. Second, your code with DIR is wrong because you did not quote the `$1` variable. As a result, if it expands to multiple fields, an error will occur.
Roman Cheplyaka
+5  A: 

That syntax is parameter expansion:

${parameter:−word}
If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

So if $1 is unset or null, it evaluates to "/tmp" and to the value of $1 otherwise.

Gumbo
Thanks for the useful link.