【Shell】設置變量默認值,參數默認值, 自動賦值

設置變量默認值,參數默認值, 自動賦值

轉自: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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章