shell-字符串多操作符综合实践多案例

1. 字符串测试举例
     提示:下面的$file并未定义,而$file1 在上面测试中已定义。
  范例1:单条件字符串测试:

[root@test-1 ~]# file1=/etc/services;file2=/etc/rc.local
[root@test-1 ~]# echo $file1 $file2
/etc/services /etc/rc.local
[root@test-1 ~]# [ -n "$file" ] && echo 1 ||echo 0
0
#若串长度不为0则真。因$file未定义长度为0,所以为假(0)
[root@test-1 ~]# [ -z "$file" ] && echo 1 ||echo 0
1
#若串长度为0则真。因$file未定义长度为0,所以为真(1)
[root@test-1 ~]# [ -n "$file1" ] && echo 1 ||echo 0
1
#若串长度不为0则真。因$file已定义变量长度不为0,所以为真(1)
[root@test-1 ~]# [ -z "$file1" ] && echo 1 ||echo 0
0
#若串长度为0则真。因$file已定义变量长度不为0,所以为假(0)

提示:去掉双引号看看
[root@test-1 ~]# [ -n $file ] && echo 1 ||echo 0
1
[root@test-1 ~]# [ -z $file1 ] && echo 1 ||echo 0
0
提示:字符串比较一定要加双引号

 范例2(生产):系统脚本/etc/init.d/nfs字符串测试的应用:

# Remote quota server
[ -z "$RQUOTAD" ] && RQUOTAD=`type -path rpc.rquotad`
[ -z "$MOUNTD_NFS_V2" ] && MOUNTD_NFS_V2=default
[ -z "$MOUNTD_NFS_V3" ] && MOUNTD_NFS_V3=default

# Number of servers to be started by default
[ -z "$RPCNFSDCOUNT" ] && RPCNFSDCOUNT=8
[ -n "$NLM_GRACE_PERIOD" ] && {
	/sbin/sysctl -w fs.nfs.nlm_grace_period=$NLM_GRACE_PERIOD >/dev/null 2>&1
}

 范例3:多条件字符串测试:

[root@test-1 ~]# file1=/etc/services;file2=/etc/rc.local
[root@test-1 ~]# echo $file1 $file2
/etc/services /etc/rc.local
[root@test-1 ~]# [ -n "$file" ] && echo 1 ||echo 0
0
#若串长度不为0则真。因$file未定义长度为0,所以为假(0)
[root@test-1 ~]# [ -z "$file" ] && echo 1 ||echo 0
1
#若串长度为0则真。因$file未定义长度为0,所以为真(1)
[root@test-1 ~]# [ -z "$file1" ] && echo 1 ||echo 0
0
[root@test-1 ~]# [ -z "$file1" -a -z "file2" ] && echo 1 ||echo 0
0
[root@test-1 ~]# [[ -z "$file1" && -z "file2" ]] && echo 1 ||echo 0
0
[root@test-1 ~]# [[ -z "$file1" || -n "file2" ]] && echo 1 ||echo 0
1
[root@test-1 ~]# [ -z "$file1" -o -z "file2" ] && echo 1 ||echo 0
0
[root@test-1 ~]# [ -n "$file1" -o -z "file2" ] && echo 1 ||echo 0
1
[root@test-1 ~]# [ "$file1" == "file2" ] && echo 1 ||echo 0
0
[root@test-1 ~]# [ "$file1" = "file2" ] && echo 1 ||echo 0
0
[root@test-1 ~]# [ "$file1" !== "file2" ] && echo 1 ||echo 0
-bash: [: !==: binary operator expected
0
[root@test-1 ~]# [ "$file1" != "file2" ] && echo 1 ||echo 0
1
[root@test-1 ~]# [ ! "$file1" == "file2" ] && echo 1 ||echo 0
1
[root@test-1 ~]# [ ! "$file1" \> "file2" ] && echo 1 ||echo 0
1
[root@test-1 ~]# [ ! "$file1" \< "file2" ] && echo 1 ||echo 0
0
[root@test-1 ~]# [ ! "${#file1}" \< "${#file2}" ] && echo 1 ||echo 0
1

  

shell-字符串多操作符综合实践多案例

上一篇:linux网卡信息获取


下一篇:关于虚拟机VMware15的安装和CentOS系统的安装