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

Posted 七月流星雨

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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-字符串多操作符综合实践多案例的主要内容,如果未能解决你的问题,请参考以下文章

代码片段:Shell脚本实现重复执行和多进程

MySQL例题一 综合案例(多条件组合查询)

MySQL例题一 综合案例(多条件组合查询)

正则表达式多用法

阿里云名师课堂Java面向对象开发41:第03个代码模型综合案例:数据表与简单Java类(一对多)

IPC一个综合小实践