shell if语句 文件测试 逻辑操作 短路操作

2015-05-31 20:19:00
admin
原创 2430
摘要:shell if语句 文件测试 逻辑操作 短路操作

一、if语句

条件测试:

1、命令执行,0为成功,改变$?的值

2、[]条件判断,0为成功,改变$?的值,[]等价于test命令;

原则:

1、取变量值最好加上双引号,整数或者字符串都是如此;

2、推荐使用字符串操作,避免使用整数操作


测试文件和目录:

if [ -f "$1" ] ;then
echo file
elif [ -d "$1" ] ;then
echo dir
fi


测试文件类型:

if [ -c "$1" ];then
echo char
elif [ -b "$1" ];then
echo block
elif [ -s "$1" ];then
echo not zero
fi


测试文件属性:

-r file 文件可读
-w file 文件可写
-x file 文件可执行

-e file 文件、链接、目录存在
-f file 普通文件
-d file 普通目录
-c file 特殊字符文件,比如/dev/null
-b file 特殊块文件
-s file 文件大小非0时为真,目录恒为真


比较操作:

[-n] STRING the length of STRING is nonzero,-n "$str"等价于"$str"
-z STRING the length of STRING is zero
STRING1 = STRING2 the strings are equal
STRING1 != STRING2 the strings are not equal
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


逻辑操作:

取反,!
逻辑与,-a
逻辑或,-o


短路操作:

[ -f /var/run/dhcpd.pid ] && echo "exists"
[ -f /usr/sbin/dhcpd ] || echo "not exists"

exec success && echo success

exec failed || echo failed

发表评论
评论通过审核之后才会显示。