shell脚本中if判断
2017-09-04 21:12
246 查看
今天在写一个自动打包文件,并清理文件的shell用if判断时发现了一些问题
最开始的脚本:
运行的时报错integer expression expected
原因为:有太多结果满足report*,就相当于在一直问系统这个文件是否存在,而这些判断条件之间又没有与或非的关系,故而出现错误,因此在if判断中不能使用通配符。
解决方法:
通过report=
另外这里有个很细节的地方,就是在定义report这个变量时,不能使用“”而要用 反引号“。
顺便回忆下if判断的用法:
if语句格式
条件表达式
这里要特别强调一点,-eq等表达式只能比较数值,不能比较字符串,要比较字符串需要用=或!=,并且shell中没有==。
最开始的脚本:
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中没有==。
相关文章推荐
- [Linux] shell脚本之if判断
- shell脚本中 if 判断中选项含义
- shell脚本中的if判断条件 详解
- Shell脚本IF条件判断和判断条件总结
- shell脚本之判断 if,elif, case
- Shell脚本IF条件判断和判断条件总结
- 20.5 Shell脚本中的逻辑判断;20.6 文件目录属性判断;20.7 if特殊用法;20.8 20.9 cace判断(上下)
- linux学习第六十四篇:Shell脚本中的逻辑判断,文件目录属性判断, if特殊用法,case判断
- Shell脚本IF条件判断和判断条件总结
- shell脚本--if判断(数字条件、字符串条件)
- 20.5 shell脚本中的逻辑判断 20.6 文件目录属性判断20.7 if 特殊用法 20.8/20.9 case判断
- Shell脚本IF条件判断和判断条件总结
- Shell脚本IF条件判断和判断条件
- shell脚本中的逻辑判断,文件目录属性判断,if特殊用法,case语句
- shell脚本if判断语句报错[: too many arguments的两种原因
- Shell脚本IF条件判断和判断条件总结
- shell脚本中的逻辑判断-文件目录属性判断-if特殊用法-case判断
- shell 脚本之判断语句 if 详解
- shell脚本if判断语句报错[: too many arguments的两种原因
- shell脚本--if判断(数字条件、字符串条件)