Shell中,可以通过冒号后面跟字符的形式,完成一定的功能,下面做具体介绍:
一: 变量操作
格式:
${VAR_NAME:-} ${VAR_NAME:?} ${VAR_NAME:=}
功能:
-:在VAR_NAME为空,将-后面的内容赋值给其他变量,VAR_NAME不会被赋值;VAR_NAME不为空,将VAR_NAME的值赋给其他变量;见Exp1。
?: 在VAR_NAME为空,不会将?后的值传给其他变量,而是返回打印到屏幕,类似提示信息;VAR_NAME不为空,将其值赋值给其他变量;见Exp2。
=:无论VAR_NAME是否为空,将=后的内容先赋值给VAR_NAME,在将其赋值给其他变量;如果VAR_NAME不为空,VAR_NAME不变,并将VAR_NAME赋值给其他变量;见Exp3。
Exp1:
[lius@VM_0_9_centos ~]$ unset A B C
[lius@VM_0_9_centos ~]$ echo $A $B $C
[lius@VM_0_9_centos ~]$ A=Hello
[lius@VM_0_9_centos ~]$ B=${A:-UNSET}
[lius@VM_0_9_centos ~]$ echo $B
Hello
[lius@VM_0_9_centos ~]$ echo $A
Hello
[lius@VM_0_9_centos ~]$ unset A B C
[lius@VM_0_9_centos ~]$ A=
[lius@VM_0_9_centos ~]$ B=${A:-UNSET}
[lius@VM_0_9_centos ~]$ echo $B
UNSET
[lius@VM_0_9_centos ~]$ echo $A
[lius@VM_0_9_centos ~]$
Exp2:
[lius@VM_0_9_centos ~]$ unset A B C
[lius@VM_0_9_centos ~]$ A=Hello
[lius@VM_0_9_centos ~]$ B=${A:?"Not defined..."}
[lius@VM_0_9_centos ~]$ echo $A
Hello
[lius@VM_0_9_centos ~]$ echo $B
Hello
[lius@VM_0_9_centos ~]$ unset A B C
[lius@VM_0_9_centos ~]$ A=
[lius@VM_0_9_centos ~]$ B=${A:?"Not defined..."}
-bash: A: Not defined...
[lius@VM_0_9_centos ~]$ echo $A
[lius@VM_0_9_centos ~]$ echo $B
[lius@VM_0_9_centos ~]$
Exp3:
[lius@VM_0_9_centos ~]$ unset A B C
[lius@VM_0_9_centos ~]$ A=Hello
[lius@VM_0_9_centos ~]$ B=${A:=UNSET}
[lius@VM_0_9_centos ~]$ echo $A
Hello
[lius@VM_0_9_centos ~]$ echo $B
Hello
[lius@VM_0_9_centos ~]$ unset A B C
[lius@VM_0_9_centos ~]$ A=
[lius@VM_0_9_centos ~]$ B=${A:=UNSET}
[lius@VM_0_9_centos ~]$ echo $A
UNSET
[lius@VM_0_9_centos ~]$ echo $B
UNSET
[lius@VM_0_9_centos ~]$
二: 字符串操作
字符串截取1-8:
expr substr "$a" 1 8
echo $a |awk '{print substr(,1,8)}'
echo $a |cut -c1-8
echo $a |dd bs=1 count=8 2>/dev/null
字符串比较/匹配:
[[ "a.txt" == a* ]] # 逻辑真 (pattern matching)
[[ "a.txt" =~ .*\.txt ]] # 逻辑真 (regex matching)
[[ "abc" == "abc" ]] # 逻辑真 (string comparision)
[[ "11" < "2" ]] # 逻辑真 (string comparision), 按ascii值比较
转载请注明:liutianfeng.com » shell中的变量操作:-/=/?