Linux中if语句用法总结

shell中的逻辑判断一般用if语句,if语句中通常用[]来表示条件测试,可以比较字符串、判断文件是否存等。备注:[ ] 中表达式两边与括号之间要有空格
if … else 语句常用基本的语法如下:
1.if [];then fi 语句
建一个测试脚本test.sh如下

#!/bin/bash
a=$1
b=$2
if [ $a == $b ];then
   echo "a and b is equal"
fi
if [ $a != $b ];then
   echo "a and b is not equal"
fi

执行命令sh test.sh 2 3给参数$1和$2赋值2和3,输出结果a and b is not equal
不加else的if语句表达式成立执行then后面的语句,表达式不成立则不执行任何命令。
2.if [];then else fi 语句

  if [ expression ];then
        executed Statement_expression_true
        else
        executed Statement_expression_false
    fi

备注:expression表达式 和方括号[ ]之间必须有空格,否则会有语法错误。如果表达式成立,then后面的语句将会被执行;如果表达式不成立则执行else后面的语句。

3.if [];then elif []; then else fi 语句,哪个expression表达式成立则执行哪个then后面的语句,否则执行else后面的语句。

if [ expression1 ];then
    executed Statement_expression1_true
 elif [ expression2 ];then
    executed Statement_expression2_true
 else
    executed Statement_expression1_2_false
 fi
#!/bin/bash
a=$1
b=$2
if [ $a == $b ];then
   echo "a and b is equal"
elif [ $a -lt $b ];then
   echo "a less than b"
else
   echo "a bigger than b"  
fi

例如建个测试脚本test.sh如上,执行命令sh test.sh 2 3给参数$1$2赋值23,输出结果a less than b;执行sh test.sh 3 2 结果为a bigger then b

#!/bin/bash
a=$1
b=$2
if [ $a == $b ];then
   echo "a and b is equal"    
else
   if [ $a -lt $b ];then
     echo "a less than b"        
   else
      echo "a bigger than b"        
   fi
fi

上述脚本,if … else 语句嵌套使用的效果与if … elif … fi 语句效果类似,但是if … elif … fi 语句要精简些

4.if … else 语句也经常与 test 命令结合使用,test 命令用于检查某个条件是否成立,与方括号[ ]功能类似

#!/bin/bash
a=$1
b=$2
if test $a == $b;then
   echo "a and b is equal"
else
   echo "a and b is not equal"  
fi

例如上述脚本,其中if test $a == $b;if [ $a == $b ];效果一样。

5.if语句常用命令选项有:
==或= : 等于 if [ $a = $b ]
-eq : 等于 if [ $a -eq $b ]
-ne :不等于 if [ $a -ne $b ]
-gt :大于 if [ $a -gt $b ]
-ge :大于等于 if [ $a -ge $b ]
-lt :小于 if [ $a -lt $b ]
-le :小于等于 if [ $a -le $b ]
-x : 判断文件是否有可执行权限 if [ -x filename ]
-n :判断$var变量是否有值 if [ -n $var ]
-d :检查目录是否存在 if [ -d filename ]
-s :判断文件大小是否为0 if [ -s filename ]
-f :检查某文件是否存在 if [ -f filename ]

例如下面脚本判断压缩包文件是否存在

#!/bin/bash 
Day=`date -d yesterday +%Y%m%d` 
FILE=access_${Day}.log.tgz
WORK_DIR= /data/nginx/logs
if [ -f ${WORK_DIR}/${FILE} ];then 
 echo "OK" 
else 
 echo "${FILE} backup fail" > error.log 
fi
发布了52 篇原创文章 · 获赞 7 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/hyfstyle/article/details/90513895