【Shell】设置变量默认值,参数默认值, 自动赋值
生活随笔
收集整理的這篇文章主要介紹了
【Shell】设置变量默认值,参数默认值, 自动赋值
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
設(shè)置變量默認(rèn)值,參數(shù)默認(rèn)值, 自動(dòng)賦值
轉(zhuǎn)自:https://zhuanlan.zhihu.com/p/98636736
默認(rèn)參數(shù)(變量默認(rèn)值)
if 繁瑣方式
if [ ! $1 ]; then$1='default' fi- 變量為null
取默認(rèn)值變量 為 null ${vari-defaultValue}# 實(shí)踐 [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時(shí), 同時(shí)改變變量值
[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 或 空字符串
取默認(rèn)值變量為null 變量為空字符串 ${vari:-defaultValue}:= 變量為null 或 空字符串, 同時(shí)改變變量值
{$vari:=defaultValue}測(cè)試 null[root@yjx214 /]# unset name[root@yjx214 /]# echo ${name:=yjx} yjx [root@yjx214 /]# echo ${name} yjx [root@yjx214 /]# 測(cè)試 空字符串[root@yjx214 /]# name="" [root@yjx214 /]# echo ${name:=yjx} yjx [root@yjx214 /]# echo $name yjx:? 變量為null 或 空字符串時(shí)報(bào)錯(cuò)并退出
[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:+ 變量不為空時(shí)使用默認(rèn)值 (與 :- 相反)
[root@yjx214 /]# name="guest" [root@yjx214 /]# echo ${name:+yjx} yjx [root@yjx214 /]# echo $name guest總結(jié)
以上是生活随笔為你收集整理的【Shell】设置变量默认值,参数默认值, 自动赋值的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【运维】日常笔记
- 下一篇: 【Echarts 3.x】填坑记