变量判断与设置

时间:2022-07-23
本文章向大家介绍变量判断与设置,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

声明:以下内容引用自鸟哥私房菜

-符号:

[root@localhost test]# username=${username-root}
[root@localhost test]# echo $username
root
[root@localhost test]# username="ric"
[root@localhost test]# username=${username-peter}
[root@localhost test]# echo $username
ric

以上重点关注username=${username-root}这一行,这行中的-表示,当username变量不存在时,${username-root}返回的值是root,由于username不存在,所以最后username的值是root,在username=${username-peter}之前,我将username赋值为ric,由于username的值存在,所以最后username的值依然是ric。所以在${variable-str}中,-表示,当variable这个变量不存在时,整个表达式的值就是str,否则表达式的值是variable。注意,当变量variable是空字符串时依然表示变量是存在的。

[root@localhost test]# username=""
[root@localhost test]# echo $username

[root@localhost test]# echo ${username-root}

上面由于我已经将username设置为空字符串,所以${username-root}的值为空字符串,如果想当username的值为空字符串时,结果依然是root,可以使用下面的方法。

[root@localhost test]# echo ${username:-root}
root

/${variable:-str}在-符号前面加上:表示,当变量variable不存在或者为空字符串时,表达式的值是str,否则表达式的值是variable。

+符号:

+和-符号的作用是相反的,如下所示:

[root@localhost test]# username="ric"
[root@localhost test]# echo ${username+root}
root
[root@localhost test]# unset username
[root@localhost test]# echo ${username+root}

当username存在时,值为root,当username不存在时,值为username。如果想让username为空字符串时值依然为username,可以在+前面加一个:号。

[root@localhost test]# username=""
[root@localhost test]# echo ${username+root}
root
[root@localhost test]# echo ${username:+root}

=符号:

[root@localhost test]# unset username
[root@localhost test]# echo ${username=root}
root
[root@localhost test]# echo $username
root
[root@localhost test]# username="ric"
[root@localhost test]# echo ${username=root}
ric
[root@localhost test]# echo $username
ric

/${variable=str}表示,当variable不存在时variable赋值为str,且表达式的值是variable,也就是str。当variable存在时,表达式的值是variable,variable的值不变。如果想让variable为空字符串时,variable被赋值为str,表达式的值为variable(也就是str)。可以在=前面加上:。

?符号:

如果我希望当变量不存在时,提示我变量不存在,并输出到stderr。可以这样实现。

[root@localhost test]# unset username
[root@localhost test]# unset var
[root@localhost test]# var=${username?无此变量}
-bash: username: 无此变量
[root@localhost test]# username="ric"
[root@localhost test]# var=${username?无此变量}
[root@localhost test]# echo $var
Ric

var=${variable?expr}中?的作用表示,当variable不存在时将expr输出到stderr(错误提示)。当variable存在时${variable?expr}表达式的值是variable。如果想让当variable为空字符串时依然将expr输出到stderr,则可以在?前面加上:。

[root@localhost test]# username=""
[root@localhost test]# var=${username:?无此变量}
-bash: username: 无此变量

总结

可以将-,+,=,?四个符号的作用总结成如下的表格:

变量设定方式

str没有设定

str为空字符串

str已设定为非空字符串

var=${str-expr}

var=expr

var=$str

var=$str

var=${str:-expr}

var=expr

var=expr

var=$str

var=${str+expr}

var=$str

var=expr

var=expr

var=${str:+expr}

var=$str

var=$str

var=expr

var=${str=expr}

str=expr var=expr

str 不变 var=

str 不变 var=$str

var=${str:=expr}

str=expr var=expr

str=expr var=expr

str 不变 var=$str

var=${str?expr}

expr 输出至 stderr

var=$str

var=$str

var=${str:?expr}

expr 输出至 stderr

expr 输出至 stderr

var=$str