views:

318

answers:

3

I am new to bash but have done lots of PHP, and Javascript.

Is there some sort of equivilent to this PHP?

$default = 10;
$var = (!$var) ? $default : $var;

Thanks

+2  A: 

Yes!

From the man page:

${parameter:-word}
      Use  Default  Values.  If parameter is unset or null, the expansion of word
      is substituted.  Otherwise, the value of parameter is substituted.
${parameter:=word}
      Assign Default Values.  If parameter is unset or null, the expansion of word
      is assigned to  parameter. The  value  of  parameter is then substituted.
      Positional parameters and special parameters may not be assigned to in this way.
${parameter:?word}
      Display Error if Null or Unset.  If parameter is null or unset, the expansion of word (or a message  to
      that effect if word is not present) is written to the standard error and the shell, if it is not inter‐
      active, exits.  Otherwise, the value of parameter is substituted.
${parameter:+word}
      Use Alternate Value.  If parameter is null or unset, nothing is substituted, otherwise the expansion of
      word is substituted.
bstpierre
+4  A: 

Why, yes, it does:

var=${var:-10}

Even with other variables:

unset var
export def=99
echo ${var:-${def}} # gives '99'
export var=7
echo ${var:-${def}} # gives '7'
paxdiablo
perfect! exactly what I was looking for. Need to use *other* variables for sure.
nicholas.alipaz
Strictly speaking, `export` is not needed here.
Dennis Williamson
+1  A: 
$ default=10
$ var=${var:-$default}
$ echo $var
10
$ var=9
$ var=${var:-$default}
$ echo $var
9
DigitalRoss
putting exactly this: http://bash.pastebin.com/f4e14cd53 into a file and executing it echos nothing to the console window.
nicholas.alipaz
I must have done something wrong, that does actually work
nicholas.alipaz
btw, your answer was great too! I just like the extra brackets ;)
nicholas.alipaz
no worries, i will probably hit the 200 point max today, like I did yesterday. more points would be wasted anyway. :-) :-)
DigitalRoss