shell编程——条件表达式和if判断
1、条件表达式
比较项 | test命令或者[] | [[]]:两个中括号 |
---|---|---|
共同点 | 都用于判断,不支持正则表达式 | 用于判断,支持正则表达式 |
区别 | 1、与或非:-a、-o、! 2、不支持正则表达式 | 1、与或非:&&、||、! 2、支持正则表达式 |
应用场景 | 用于条件判断 | 用于条件判断 |
- 要查看test命令的判断条件可以查询man手册:man test
2、if判断
2.1、if分支结构
if [ 条件表达式 ];then条件成立要执行的命令
elif [ 条件表达式 ];then条件成立要执行的命令
else条件成立要执行的命令
fi
2.2、示例代码
if [ -d /mnt/hgfs/share_file_Ubuntu/shell ];thenecho "目录存在"
fiif [ -d /mnt/hgfs/share_file_Ubuntu/shell ];thenecho "目录存在"
elseecho "目录不存在"
fiif [ -d /mnt/hgfs/share_file_Ubuntu/777 ];thenecho "11111"
elif [ -d /mnt/hgfs/share_file_Ubuntu/shell ];thenecho "2222"
elseecho "3333"
fi
3、文件判断选项
FILE1 -ef FILE2FILE1 and FILE2 have the same device and inode numbersFILE1 -nt FILE2FILE1 is newer (modification date) than FILE2FILE1 -ot FILE2FILE1 is older than FILE2-b FILEFILE exists and is block special-c FILEFILE exists and is character special-d FILEFILE exists and is a directory-e FILEFILE exists-f FILEFILE exists and is a regular file-g FILEFILE exists and is set-group-ID-G FILEFILE exists and is owned by the effective group ID-h FILEFILE exists and is a symbolic link (same as -L)-k FILEFILE exists and has its sticky bit set-L FILEFILE exists and is a symbolic link (same as -h)-O FILEFILE exists and is owned by the effective user ID-p FILEFILE exists and is a named pipe-r FILEFILE exists and read permission is granted-s FILEFILE exists and has a size greater than zero-S FILEFILE exists and is a socket-t FD file descriptor FD is opened on a terminal-u FILEFILE exists and its set-user-ID bit is set-w FILEFILE exists and write permission is granted-x FILEFILE exists and execute (or search) permission is granted
4、字符串判断选项
-n STRINGthe length of STRING is nonzeroSTRING equivalent to -n STRING-z STRINGthe length of STRING is zeroSTRING1 = STRING2the strings are equalSTRING1 != STRING2the strings are not equal
5、整数判断选项
INTEGER1 -eq INTEGER2INTEGER1 is equal to INTEGER2INTEGER1 -ge INTEGER2INTEGER1 is greater than or equal to INTEGER2INTEGER1 -gt INTEGER2INTEGER1 is greater than INTEGER2INTEGER1 -le INTEGER2INTEGER1 is less than or equal to INTEGER2INTEGER1 -lt INTEGER2INTEGER1 is less than INTEGER2INTEGER1 -ne INTEGER2INTEGER1 is not equal to INTEGER2
6、示例代码
#!/bin/bash#判断文件
if [ -d /mnt/hgfs/share_file_Ubuntu/shell ];thenecho "目录存在"
elseecho "目录不存在"
fi#判断字符串
string1="abc"
string2=if [ "string1" != "string2" ]; thenecho "string1 != string2"
fiif [ "string1" ]; thenecho "string1 is nonzero"
fi#判断数字
num1=44
num2=55if [ $num1 -lt $num2 ]; thenecho "num1 < num2"
elseecho "num1 >= num2"
fi#双中括号,使用整数判断可以直接使用大于号、等于号、小于号
if [[ $num1 < $num2 ]]; thenecho "num1 < num2"
elseecho "num1 >= num2"
fi#双中括号可以使用正则表达式
if [[ $num1 =~ [0-9] ]];thenecho "num1包含数字"
fi#实现判断条件的与操作
if [ -n "string1" ] && [ -n "string2" ];thenecho "12345"
fi
7、运行结果
rlk@rlk:shell$ ./test.sh
目录存在
string1 != string2
string1 is nonzero
num1 < num2
num1 < num2
num1包含数字
12345