Bash 参数替换中的 :- 和 := 有什么区别?

What's the difference between :- and := in Bash parameter substitution?

Bash 参数替换中的 :- 和 := 有什么区别?

他们似乎都设置了默认值?

引用 Bash Reference Manual:

${parameter:-word}

If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

${parameter:=word}

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.

区别在于:=不仅替代了word,它还分配parameter:

var=
echo "$var"               # prints nothing
echo "${var:-foo}"        # prints "foo"
echo "$var"               # $var is still empty, prints nothing
echo "${var:=foo}"        # prints "foo", assigns "foo" to $var
echo "$var"               # prints "foo"

查看这个很棒的 wiki.bash-hackers.org tutorial 了解更多信息。

$ var=
$ echo $(( ${var:-1} + 3 ))  # local substitution if value is null
4
$ echo $(( ${var} + 3 ))
3

# set it to null 
$ var= 
$ echo $(( ${var:=1} + 3 )) # global substitution if value is null
4
$ echo $(( ${var} + 3 ))
4 

https://www.tldp.org/LDP/abs/html/parameter-substitution.html

来自 https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html :

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

${parameter:=word}
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.

In :- 不修改参数值,只是'prints'字的扩展。在 := 中,参数获取新值,即单词的扩展以及它 'print' 单词的扩展。
有时在脚本中,如果未设置变量,您希望为其分配一个默认值。许多人使用 VAR=${VAR:-1},如果未设置 VAR,它会将“1”分配给 VAR。这也可以写成 : ${VAR:=1},如果 VAR 没有被设置并且 运行 : $VAR: 1,它会将 '1' 赋给 VAR,但是 : 是bash 中的一个特殊内置函数,将丢弃所有参数而不执行任何操作。