怎么理解 - 和:=在bash?

时间:2012-05-02 14:55:19

标签: bash

JOBS=${JOBS:="-j2"}

dir=${1-/usr/src}

此处:=-的含义是什么?

我猜他们可以作为某种默认,那有什么不同呢?

2 个答案:

答案 0 :(得分:2)

man bashParameter Expansion部分)将回答这些问题和相关问题。

摘录:

   ${parameter:-word}
          Use Default Values.  If parameter is unset or null, the expansion of word is substituted.  Otherwise, the value of parame‐
          ter 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 interactive, 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  substi‐
          tuted.

答案 1 :(得分:2)

对于:=(以及相关的=),您可以使用内置的“:”命令来评估参数,而无需将其分配给自身:

# Set JOBS=-j2 if JOBS is not set or equal to ""
: ${JOBS:='-j2'}

# Set JOBS=-j2 if JOBS is not set. Don't change if JOBS is already set to ""
: ${JOBS='-j2'}

对于:--,请勿更改变量的值;只需在其位置使用第二个值:

# Set dir to /usr/src if $1 is not set, but don't set $1 itself
dir=${1-/usr/src}

# Set dir to /usr/src if $1 is not set or set to "", but don't set or change $1
dir=${1:-/usr/src}