test表达式
1、表达式用法
test表达式 | |
运算符 | 如果……则为真 |
string | string不是null |
“-b file” | file是块设备文件 |
“-c file” | file是字符设备文件 |
“-d file” | file是目录 |
“-e file” | file存在 |
“-f file” | file为一般文件 |
“-g file” | file有设置它的setgid位 |
“-h file” | file是一符号连接 |
“-L file” | file是一符号连接(等同于 -h) |
“-n string” | string是非null |
“-p file” | file是一命名的管道(FIFO文件) |
“-r file” | file是可读的 |
“-S file” | file是socket |
“-s file” | file不是空的 |
“-t n” | 文件描述符n指向一终端 |
“-u file” | file有设置他的setuid位 |
“-w file” | file是可写入的 |
“-x file” | file是可执行的,或file是可被查找的目录 |
“-z string” | string为null |
s1 = s2 | 字符串s1与s2相同 |
s1 != s2 | 字符串s1与s2不相同 |
n1 -eq n2 | 整数n1等于n2 |
n1 -ne n2 | 整数n1不等于n2 |
n1 -lt n2 | n1小于n2 |
n1 -gt n2 | n1大于n2 |
n1 -le n2 | n1小于或等于n2 |
n1 -ge n2 | n1大于或等于n2 |
2、案列
2.1 test -f
1 #! /bin/bash
2 #if judagement condition expression
3 FILE=$1
4 echo $FILE
5 if test -f $FILE
6 then
7 echo "$FILE exists and it is a normal file"
8 else
9 echo "$FILE doesn't exit!!"
10 fi
andy@andy-virtual-machine:~/test_shell$ ./example1.sh 3.txt
3.txt
3.txt doesn't exit!!
andy@andy-virtual-machine:~/test_shell$ ./example1.sh 1.txt
1.txt
1.txt exists and it is a normal file
andy@andy-virtual-machine:~/test_shell$ ./example1.sh 2.txt
2.txt
2.txt exists and it is a normal file
andy@andy-virtual-machine:~/test_shell$ ./example1.shexists and it is a normal file
andy@andy-virtual-machine:~/test_shell$ test -f
andy@andy-virtual-machine:~/test_shell$ echo $?
0
andy@andy-virtual-machine:~/test_shell$ test -f 1.txt
andy@andy-virtual-machine:~/test_shell$ echo $?
0
andy@andy-virtual-machine:~/test_shell$ test -f 3.txt
andy@andy-virtual-machine:~/test_shell$ echo $?
1
andy@andy-virtual-machine:~/test_shell$ vim example1.sh
andy@andy-virtual-machine:~/test_shell$ ls -l
total 4
-rw-rw-r-- 1 andy andy 0 2021-03-04 22:20 1.txt
-rw-rw-r-- 1 andy andy 0 2021-03-04 22:20 2.txt
-rwxrw-r-- 1 andy andy 173 2021-03-04 22:16 example1.sh
Tips:test -f file表达式,若file文件存在且为普通文件,则退出状态为0,if 语句中若退出状态为0,则表示满足,会执行对应的语句。当文件为空时,test -f 退出状态也为0。若文件名用双引号包围,那么就不会出现文件名为空是测试表达式退出状态也为0。
2.2 test -e
1 #! /bin/bash
2 #if judagement condition expression
3 FILE=$1
4 echo $FILE
5 if test -e $FILE
6 then
7 echo "$FILE exists and it is a normal file"
8 else
9 echo "$FILE doesn't exist!!"
10 echo "create file $FILE automatically"
11 touch $FILE
12 fi
13
2.3 string
andy@andy-virtual-machine:~/test_shell$ test 111
andy@andy-virtual-machine:~/test_shell$ echo $?
0
andy@andy-virtual-machine:~/test_shell$ test
andy@andy-virtual-machine:~/test_shell$ echo $?
1
2.4 -n/-z string
andy@andy-virtual-machine:~/test_shell$ test -n "111"
andy@andy-virtual-machine:~/test_shell$ echo $?
0
andy@andy-virtual-machine:~/test_shell$