您的位置:首页 > 运维架构 > Shell

shell脚本中if判断

2017-09-04 21:12 246 查看
今天在写一个自动打包文件,并清理文件的shell用if判断时发现了一些问题

最开始的脚本:

cd /ycl/domain/smp/smp_hb/processed
if [ !-f "report_${time}*" ];then
echo "Sorry,the file report_${time}.josn is not exit"
exit
else
tar -zcvf report_${time}.tar report_${time}*
rm -f report_${time}*.json
fi


运行的时报错integer expression expected

原因为:有太多结果满足report*,就相当于在一直问系统这个文件是否存在,而这些判断条件之间又没有与或非的关系,故而出现错误,因此在if判断中不能使用通配符

解决方法:

cd /ycl/domain/smp/smp_hb/processed
report=`find report_${time}* &> /dev/null;echo $?`
if [ "$report" -eq "1"  ];then
echo "Sorry,the file report_${time}.josn is not exit"
else
tar -zcvf report_${time}.tar report_${time}*
rm -f report_${time}*.json
fi


通过report=
find report_${time}* &> /dev/null;echo $?
的返回值来判断是否report*的文件存在,文件存在返回0,反之则为1

另外这里有个很细节的地方,就是在定义report这个变量时,不能使用“”而要用 反引号“。

顺便回忆下if判断的用法:

if语句格式

if  条件
then
Command
else
Command
fi


条件表达式

文件表达式
if [ -f  file ]    如果文件存在
if [ -d ...   ]    如果目录存在
if [ -s file  ]    如果文件存在且非空
if [ -r file  ]    如果文件存在且可读
if [ -w file  ]    如果文件存在且可写
if [ -x file  ]    如果文件存在且可执行
整数变量表达式
if [ int1 -eq int2 ]    如果int1等于int2
if [ int1 -ne int2 ]    如果不等于
if [ int1 -ge int2 ]       如果>=
if [ int1 -gt int2 ]       如果>
if [ int1 -le int2 ]       如果<=
if [ int1 -lt int2 ]       如果<

字符串变量表达式
If  [ $a = $b ]                 如果string1等于string2

8d06
字符串允许使用赋值号做等号
if  [ $string1 !=  $string2 ]   如果string1不等于string2
if  [ -n $string  ]             如果string 非空(非0),返回0(true)
if  [ -z $string  ]             如果string 为空
if  [ $sting ]                  如果string 非空,返回0 (和-n类似)


这里要特别强调一点,-eq等表达式只能比较数值,不能比较字符串,要比较字符串需要用=或!=,并且shell中没有==。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: