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 ];then
echo "目录存在"
fi
if [ -d /mnt/hgfs/share_file_Ubuntu/shell ];then
echo "目录存在"
else
echo "目录不存在"
fi
if [ -d /mnt/hgfs/share_file_Ubuntu/777 ];then
echo "11111"
elif [ -d /mnt/hgfs/share_file_Ubuntu/shell ];then
echo "2222"
else
echo "3333"
fi
3、文件判断选项
FILE1 -ef FILE2
FILE1 and FILE2 have the same device and inode numbers
FILE1 -nt FILE2
FILE1 is newer (modification date) than FILE2
FILE1 -ot FILE2
FILE1 is older than FILE2
-b FILE
FILE exists and is block special
-c FILE
FILE exists and is character special
-d FILE
FILE exists and is a directory
-e FILE
FILE exists
-f FILE
FILE exists and is a regular file
-g FILE
FILE exists and is set-group-ID
-G FILE
FILE exists and is owned by the effective group ID
-h FILE
FILE exists and is a symbolic link (same as -L)
-k FILE
FILE exists and has its sticky bit set
-L FILE
FILE exists and is a symbolic link (same as -h)
-O FILE
FILE exists and is owned by the effective user ID
-p FILE
FILE exists and is a named pipe
-r FILE
FILE exists and read permission is granted
-s FILE
FILE exists and has a size greater than zero
-S FILE
FILE exists and is a socket
-t FD
file descriptor FD is opened on a terminal
-u FILE
FILE exists and its set-user-ID bit is set
-w FILE
FILE exists and write permission is granted
-x FILE
FILE exists and execute (or search) permission is granted
4、字符串判断选项
-n STRING
the length of STRING is nonzero
STRING equivalent to -n STRING
-z STRING
the length of STRING is zero
STRING1 = STRING2
the strings are equal
STRING1 != STRING2
the strings are not equal
5、整数判断选项
INTEGER1 -eq INTEGER2
INTEGER1 is equal to INTEGER2
INTEGER1 -ge INTEGER2
INTEGER1 is greater than or equal to INTEGER2
INTEGER1 -gt INTEGER2
INTEGER1 is greater than INTEGER2
INTEGER1 -le INTEGER2
INTEGER1 is less than or equal to INTEGER2
INTEGER1 -lt INTEGER2
INTEGER1 is less than INTEGER2
INTEGER1 -ne INTEGER2
INTEGER1 is not equal to INTEGER2
6、示例代码
#!/bin/bash
#判断文件
if [ -d /mnt/hgfs/share_file_Ubuntu/shell ];then
echo "目录存在"
else
echo "目录不存在"
fi
#判断字符串
string1="abc"
string2=
if [ "string1" != "string2" ]; then
echo "string1 != string2"
fi
if [ "string1" ]; then
echo "string1 is nonzero"
fi
#判断数字
num1=44
num2=55
if [ $num1 -lt $num2 ]; then
echo "num1 < num2"
else
echo "num1 >= num2"
fi
#双中括号,使用整数判断可以直接使用大于号、等于号、小于号
if [[ $num1 < $num2 ]]; then
echo "num1 < num2"
else
echo "num1 >= num2"
fi
#双中括号可以使用正则表达式
if [[ $num1 =~ [0-9] ]];then
echo "num1包含数字"
fi
#实现判断条件的与操作
if [ -n "string1" ] && [ -n "string2" ];then
echo "12345"
fi
7、运行结果
rlk@rlk:shell$ ./test.sh
目录存在
string1 != string2
string1 is nonzero
num1 < num2
num1 < num2
num1包含数字
12345