标签:des style color io 使用 ar 文件 sp on
比较和判断是程序流程控制的要素,此文总结一下shell的比较和判断语句,方便查找使用。
1. 重要的比较操作符
大于: -gt
小于: -lt
大于或等于: -ge
小于或等于: -le
等于: -eq
不等于: -ne
举例:
if [ $var -eq 0] # 如果$var等于0时
if [ $var -ne 0 -a $var -gt 2 ] #逻辑与 -a
if [ $var -ne 0 -o $var -gt 2 ] #逻辑或 -o
2. 文件相关的判断测试
[ -f $file_var ] : 如果$file_var是存在的文件路径或文件名,则返回真;
[ -x $var ] : 如果$var具有文件可执行权限,则返回真;
[ -d $var ] : 如果$var是目录,则返回真;
[ -e $var ] : 如果$var是存在的文件,则返回真;
[ -c $var ] : 如果$var是存在的字符设备文件,则返回真;
附上英文:
-a file exists.
-b file exists and is a block special file.
-c file exists and is a character special file.
-d file exists and is a directory.
-e file exists (just the same as -a).
-f file exists and is a regular file.
-g file exists and has its setgid(2) bit set.
-G file exists and has the same group ID as this process.
-k file exists and has its sticky bit set.
-L file exists and is a symbolic link.
-n string length is not zero.
-o Named option is set on.
-O file exists and is owned by the user ID of this process.
-p file exists and is a first in, first out (FIFO) special file or named pipe.
-r file exists and is readable by the current process.
-s file exists and has a size greater than zero.
-S file exists and is a socket.
-t file descriptor number fildes is open and associated with a terminal device.
-u file exists and has its setuid(2) bit set.
-w file exists and is writable by the current process.
-x file exists and is executable by the current process.
-z string length is zero.
举例:
fpath="etc/passwd"
if [ -e $fpath ]; then
echo "file exists";
else
echo "not exist";
fi
3. 字符串比较
[[ $str1 = $str2 ]] : 当str1等于str2时,返回真;
[[ $str1 == $str2 ]] : 这是判断字符串是否相等的另一种写法;
[[ $str1 != $str2 ]] : 当str1不等于str2时,返回真;
[[ $str1 > $str2 ]] : 当str1大于str2时,返回真;
[[ $str1 < $str2 ]] : 当str1小于str2时,返回真;
[[ -z $str1 ]] : 当str1包含的是空字符串,返回真;
[[ -n $str1 ]] : 当str1包含的是非空字符串,返回真;
标签:des style color io 使用 ar 文件 sp on
原文地址:http://my.oschina.net/zhangxu0512/blog/325403