Bash参数替换中的:-和:=有什么区别? [英] What's the difference between :- and := in Bash parameter substitution?

查看:86
本文介绍了Bash参数替换中的:-和:=有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆