BASH:它是否支持条件变量,如var =“test”?“1”:“2”

时间:2009-09-25 04:03:28

标签: bash variables conditional

我是bash的新手,但已经做了很多PHP和Javascript。

这个PHP有某种等效的吗?

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

由于

3 个答案:

答案 0 :(得分:12)

是的,确实如此:

var=${var:-10}

即使使用其他变量:

unset var
export def=99
echo ${var:-${def}} # gives '99'
export var=7
echo ${var:-${def}} # gives '7'

答案 1 :(得分:6)

是!

从手册页:

${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.

答案 2 :(得分:2)

$ default=10
$ var=${var:-$default}
$ echo $var
10
$ var=9
$ var=${var:-$default}
$ echo $var
9