簡體   English   中英

有什么區別: - 和:=在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 ,還將其分配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教程

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

在: - 不修改參數值,只是'打印'字的擴展。 在:=參數獲取新值,即字的擴展,並且'打印'字的擴展。
有時在腳本中,如果未設置變量,則要為變量分配默認值。 許多人使用VAR=${VAR:-1} ,如果沒有設置VAR,它將為VAR分配'1'。 這也可以寫成: ${VAR:=1} ,如果沒有設置VAR,它將為VAR分配'1'並運行: $VAR: 1 ,但是:是bash中的特殊內置函數,將丟棄所有參數什么都不做

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM