【Shell】设置变量默认值,参数默认值, 自动赋值
设置变量默认值,参数默认值, 自动赋值转自:https://zhuanlan.zhihu.com/p/98636736默认参数(变量默认值)if 繁琐方式if [ ! $1 ]; then$1='default'fi- 变量为null取默认值变量 为 null${vari-defaultValue}# 实践[root@yjx214 /]# unset name[root@yjx214 /]# ec
·
设置变量默认值,参数默认值, 自动赋值
转自:https://zhuanlan.zhihu.com/p/98636736
默认参数(变量默认值)
if 繁琐方式
if [ ! $1 ]; then
$1='default'
fi
- 变量为null
取默认值
变量 为 null
${vari-defaultValue}
# 实践
[root@yjx214 /]# unset name
[root@yjx214 /]# echo ${name}
[root@yjx214 /]# echo ${name-yjx}
yjx
[root@yjx214 /]# name=
[root@yjx214 /]# echo ${name-yjx}
[root@yjx214 /]# echo ${name}
[root@yjx214 /]#
= 变量为null时, 同时改变变量值
[root@yjx214 /]# unset name
[root@yjx214 /]# echo ${name=yjx}
yjx
[root@yjx214 /]# echo $name
yjx
[root@yjx214 /]# name=""
[root@yjx214 /]# echo ${name=yjx}
[root@yjx214 /]#
:- 变量为null 或 空字符串
取默认值
变量为null
变量为空字符串
${vari:-defaultValue}
:= 变量为null 或 空字符串, 同时改变变量值
{$vari:=defaultValue}
测试 null
[root@yjx214 /]# unset name
[root@yjx214 /]# echo ${name:=yjx}
yjx
[root@yjx214 /]# echo ${name}
yjx
[root@yjx214 /]#
测试 空字符串
[root@yjx214 /]# name=""
[root@yjx214 /]# echo ${name:=yjx}
yjx
[root@yjx214 /]# echo $name
yjx
:? 变量为null 或 空字符串时报错并退出
[root@yjx214 /]# unset name
[root@yjx214 /]# echo ${name:?yjx}
-bash: name: yjx
[root@yjx214 /]# name=""
[root@yjx214 /]# echo ${name:?yjx}
-bash: name: yjx
[root@yjx214 /]# name="guest"
[root@yjx214 /]# echo ${name:?yjx}
guest
:+ 变量不为空时使用默认值 (与 :- 相反)
[root@yjx214 /]# name="guest"
[root@yjx214 /]# echo ${name:+yjx}
yjx
[root@yjx214 /]# echo $name
guest
更多推荐

所有评论(0)