bash中if判断(转载)

本文转载:http://codingstandards.iteye.com/blog/780156    

用途说明

Shell中的条件判断语句,与其他编程语言类似。

如果需要知道有哪些条件判断方式,通过man test就可以得到帮助。

常用格式

格式一

if 条件; then
    语句
fi

示例:

if [ "foo" = "foo" ]; then  
    echo expression evaluated as true  
fi  

格式二

if 条件; then
    语句
else
    语句
fi

示例:

if [ "foo" = "foo" ]; then  
    echo expression evaluated as true  
else  
    echo expression evaluated as false  
fi  

格式三

if 条件; then
    语句
elif 条件; then
    语句
fi

示例:

#!/bin/bash
sum1=1
sum3=3
if [ ${sum1} -lt 1 ];then
   echo ${sum1}
elif [ ${sum3} -gt 2  ];then
   echo ${sum3}
fi

格式四

if 条件; then
    语句
elif 条件; then
    语句
else
    语句
fi

示例:

#!/bin/bash
#test if
sum1=1
sum2=2
sum3=3
sum4=4
if [ $sum4 -gt 0 ]   ;then
    echo "sum4>0"
elif [ $sum3 -gt 2 ] ;then 
    echo "sum3>2"
elif [ $sum2 -gt 1 ] ;then
    echo "sum2>1"
else
    echo "hello world"
fi

使用示例

示例五 判断文件中是否包含某个字符串

if grep -q root /etc/passwd; then  
    echo account root exists  
else  
    echo account root not exist  
fi  

示例六 判断文件是否存在

if [ -e myfile ]; then  
    echo myfile exists  
else  
    touch myfile  
    echo myfile created  
fi  

示例七 判断两个文件是否相同

echo 1 >file1  
echo 2 >file2  
if ! diff -q file1 file2; then  
    echo file1 file2 diff  
else  
    echo file1 file2 same  
fi   

 

posted @ 2017-09-15 13:48  splenday  阅读(473)  评论(0)    收藏  举报