为什么在 shell 脚本中设置变量有三种语法?

1 shell bash variable

root@ubuntu:~# echo ${x=1}
1
root@ubuntu:~# echo ${x:=1}
1
root@ubuntu:~# echo ${x-1}
1
root@ubuntu:~# 
Run Code Online (Sandbox Code Playgroud)

为什么在 shell 脚本中设置变量有三种语法?

具有三种语法的技术优势是什么?

甚至编程语言也不止一种。

roc*_*cky 7

这些做的事情略有不同。事实上,最后一个echo ${x-1}实际上并没有设置x,而是仅在x未设置时才替换表达式中的值 1 。

x=1另一方面,无条件地设置x

至于 := 运算符。这是来自ksh手册:

   ${parameter:=word}
          If  parameter is not set or is null then set it to word; the
          value of the parameter is then substituted.  Positional  parameters may 
          not be assigned to in this way.
Run Code Online (Sandbox Code Playgroud)

在 Ruby 中,这就像||=.

如果您查看x = 运算符系列,还有更多,:-它们是我遇到的最受欢迎的。这一个替代品来,如果变量尚未设置默认值的变量。所以你像这样使用它:

x=${1:-10}
Run Code Online (Sandbox Code Playgroud)

英文是:如果 $1 未设置,则将 10 分配给x,否则将$1 的值分配给x。在函数中,这具有为参数分配默认值的效果。所以

f() {
  typeset x
  x=${1-10}
  ...
}
Run Code Online (Sandbox Code Playgroud)

相当于Python:

def f(x=10): 
Run Code Online (Sandbox Code Playgroud)

我认为 David Korn 会承认运算符的多样性可能有点矫枉过正,但它现在是POSIX 标准的一部分,第 2.6.2 节,因此它可能会保留下来。

甚至编程语言也不止一种。

如上所述,存在一种误解,认为它们完全相同。在编程语言中,赋值语句的变体并不少见。我||=在 Ruby 中提到过。许多语言都有+=-=等等。在 Perl 中,如果您之前没有定义 $x $x += 1,那么如果您运行它,它将设置$x为 1(并且,如果您没有启用“严格”检查,那么您会感到羞耻)。