Bash参数替换中的:-和:=有什么区别? [英] What's the difference between :- and := in Bash parameter substitution?
问题描述
Bash参数替换中:-和:=有什么区别?
它们似乎都设置了默认值?
引用 Bash参考手册:
$ {parameter:-word}
如果
parameter
未设置或为null,则展开word
被替换.否则,将替换parameter
的值.
$ {parameter:= word}
如果
parameter
未设置或为null,则展开将word
分配给parameter
.然后,parameter
的值替代.位置参数和特殊参数可能不是分配给这种方式.
区别在于:=
不仅替换了 word
,还将分配给了参数代码>:
var =echo"$ var"#不输出任何内容echo"$ {var:-foo}"#打印"foo"echo"$ var"#$ var仍然为空,不输出任何内容echo"$ {var:= foo}"#打印"foo",将"foo"分配给$ varecho"$ var"#打印"foo"
有关更多信息,请参见此出色的 wiki.bash-hackers.org教程./p>
What's the difference between :- and := in Bash parameter substitution?
They seem to both set the default?
Quoting Bash Reference Manual:
${parameter:-word}
If
parameter
is unset or null, the expansion ofword
is substituted. Otherwise, the value ofparameter
is substituted.
${parameter:=word}
If
parameter
is unset or null, the expansion ofword
is assigned toparameter
. The value ofparameter
is then substituted. Positional parameters and special parameters may not be assigned to in this way.
The difference is that :=
doesn't only substitute the word
, it also assigns it to the 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"
See this great wiki.bash-hackers.org tutorial for more information.
这篇关于Bash参数替换中的:-和:=有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!