shell 中的文件、字符、数字判断等

1.直接命令:命令执行成功返回 0 不存在返回 125 内部错误返回 5,总之只要不是 0 就失败,then 中的代码不会执行

1 if command1
2 then
3     do somenthing
4 elif command2
5 then
6     do again
7 fi

2.test 命令,条件不成立 test 命令退出返回非零的退出状态码

1 if test condition
2 then
3     do something
4 fi

3. 方括号

   3.1 数值比较

option 描述
-eq 两个数值是否相等
-ge >=
-gt >
-le <=
-lt <
-ne !=

  当然也可以直接 [ $var1 > $var2  ]  这种形式,但是 > 会被解释成重定向输入 $var2 文件,所以需要转义 [ $var1 > $var2 ]  那还不如 [ $var1 -gt $var2 ] 来得好是吧

  3.2 字符串比较

option description
str1 = str2 两个字符串是否相同
str1 != str2 两个字符串是否不同
str1 > str2 1字符串的ASCII是否大于2的
str1 < str2  ASCII 值比较
-n str1

str1 字符串长度是否为0

-z str1 str1 是否为空 ‘’

  注意 >  < 符号需要转义

  3.3 文件比较

option 描述
-d file 是否是目录
-e file exist 是否存在
-f file file 是否是文件
-s file 文件是否为空
-r 是否可读
-w 是否可写
-x 是否可执行
-0  
-G  
file1 -nt file2

f1 是否比 f2 新

file1 -ot file2

f1 是否比 f2 旧

 1 xxx@ubuntu:~/data$ ls -l
 2 total 20
 3 -rw-rw-r-- 1 xxx root     5 Jun 22 08:24 1.log
 4 -rw-r--r-- 1 xxx xxx     0 Jun  7 06:16 2.log
 5 drwxrwxr-x 2 xxx  xxx  4096 Jun 21 06:46 dirx
 6 drwxrwxr-x 3 xxx xxx 4096 Jun 13 19:56 package
 7 -rw-rw-r-- 1 xxx xxx 59 Jun  6 20:06 sortx
 8 -rwxrwxr-x 1 xxx xxx 167 Jun 21 05:28 test.sh
 9 xxx @ubuntu:~/data$ file=$(pwd)/1.log
10 xxx @ubuntu:~/data$ echo $file
11 /home/xxx/data/1.log
12 xxx @ubuntu:~/data$ if [ -e $file ];then
13 > if [ -d $file ];then
14 > echo "it's directory"
15 > elif [ -f $file ];then
16 > echo "it's file"
17 > fi
18 > fi
19 it's file
20 xxx@ubuntu:~/data$
21 xxx@ubuntu:~/data$ if [ 3 -eq '3' ];then
22 > echo 'eq yes'
23 > else
24 > echo 'no'
25 > fi
26 eq yes
27 xxx@ubuntu:~/data$ if [ 3 -eq 2 ];then echo 'eq yes'; else echo 'no'; fi
28 no
29 xxx@ubuntu:~/data$ if [ 3 -ne 2 ];then echo 'eq yes'; else echo 'no'; fi
30 eq yes
31 xxx@ubuntu:~/data$ if [ 3 -lt 2 ];then echo 'eq yes'; else echo 'no'; fi
32 no
33 xxx@ubuntu:~/data$ if [ 3 -gt 2 ];then echo 'eq yes'; else echo 'no'; fi
34 eq yes
35 xxx@ubuntu:~/data$ if [ 3 -gt 3 ];then echo 'eq yes'; else echo 'no'; fi
36 no
37 xxx@ubuntu:~/data$ if [ 3 -ge 3 ];then echo 'eq yes'; else echo 'no'; fi
38 eq yes
39 xxx@ubuntu:~/data$ if [ 3 -le 3 ];then echo 'eq yes'; else echo 'no'; fi
40 eq yes
原文地址:https://www.cnblogs.com/shiqi17/p/13179917.html