[变量的条件替换]
#!/bin/bash var1=abc echo "1 $var1" echo "2 ${var1:-xx}" echo "3 $var1" unset var1 echo "4 ${var1:-yy}" var1= echo "5 ${var1:-zz}" echo "----" var2=abc echo "1 ${var2:=xx}" echo "2 $var2" var2= echo "3 ${var2:=yy}" echo "4 $var2" echo "----" var3=abc echo "1 ${var3:+xx}" echo "2 $var3" var3= echo "3 ${var3:+yy}" echo "4 $var3" echo "----" var4=abc echo "1 ${var4:?xx}" echo "2 $var4" var4= echo "3 ${var4:?xx}" echo "4 $var4"
${variable: -value} 如果有值, 并且非null,那么打印出$variable原来的值,否则输出value.
*不修改variable本身的值 test21.sh
${variable:=value} 和上面类似,但是,修改variable本身的值
${variable:+value} 如果有值且非null,那么使用value值,否则作为null.同时,不修改variable变量的值
${variable:?value} 如果有值且非null,那么使用本来的值.否则,报错退出.如果value为空,那么打印默认的一条信息
因此我们执行上面的程序, 内容打印为:
1 abc
2 abc
3 abc
4 yy
5 zz
—-
1 abc
2 abc
3 yy
4 yy
—-
1 xx
2 abc
3
4
—-
1 abc
2 abc
./test21.sh: line 34: var4: xx
或者最后一行也可能输出这样的信息:
./test21.sh: line 34: var4: parameter null or not set
本文链接:https://www.poisonbian.com/post/1098.html 转载需授权!