【linux编程】生信编程-shell脚本编程-if条件语句

2017-12-26  本文已影响0人  leadingsci

shell编程

if 条件语句

If 条件语句主要有三中形式:

1. if…then…fi 语法:

if 条件 
then     
   条件判断成立时执行的语句 
fi

这里的条件通常是一个条件测试命令 ,当条件为真 (执行命令的退出状态为0) 时执行 then 后面的语句;其也可以为一个普通的命令,当执行命令的退出状态为 0 时执行 then 后面的语句。then 可以写在 if 的 '条件' 后面,以分号相隔,也可以另起一行直接写,语句必须以 fi 结束,

例子


if echo "Hello" 
then    
    echo "world" 
fi 

str='/usr/bin/perl' 
if grep -q 'perl' "$str"; then    
    echo "I found perl in string '$str'" 
fi 

if [ 2 > 1 ]; then   
    echo "2 is bigger than 1" 
fi

2. if…then…else…fi 语法:

if 条件 
then
    条件判断成立时执行的语句 
else
    条件判断不成立时执行的语句 
fi

当 if 条件为真时执行 then 后面的语句;当 if 条件为假时执行 else 后面的语句,同样语句必须以 fi 结束

例子

a=100 
b=99 
if [[ -n $a && -n $b ]]; 
then
    if test $a -ge $b; then
        echo "a ($a) is bigger than b ($b)"
    else 
        echo "a ($a) is smaller than b ($b)"
    fi
fi

执行脚本得到结果: a (100) is bigger than b (99)


3. if…then…elif…then…else…fi

if 条件 
then
    (if) 条件判断成立时执行的语句 
elif 条件 
then
    (elif) 条件判断成立时执行的语句 
else
    (if 与 elif) 条件判断都不成立时执行的语句 
fi

语句必须以 fi 结束。可以把 fi 记成 if 的颠倒,if...fi 闭合后才形成完整的 if 语句。

例子

#!/bin/bash
set -e 
set -u 
if [[ -x example.sh ]]; then
    echo "The file 'example.sh' exists and is executable" 
elif [[ -f example.sh ]]; then
    echo "The file 'example.sh' exists but is not executable" 
else
    echo "The file 'example.sh' does not exist" 
fi

另存脚本为example3-3.sh,执行脚本;执行 touch example.sh 后执行脚本;执行 chmod +x example.sh 后再次执行脚本,将得到以下结果:


条件判断之 test, [] 与 [[]]

这三个命令都属于 shell 里面的条件测试命令,条件判断的返回状态为 0 (真) 或者 1 (假),if 基于条件测试返回的结果来决定如何执行下面的代码。

需要注意的是 [ ] 与 [[ ]] 也是命令!

故成对方括号之间的内容可以理解为条件测试的参数,根据我们前面讲过的原则,参数之间要以空格分割,所以在写条件判断时一定要注意:**用空格分割参数! **

1. 整数和字符串比较操作符:

2. 文件和目录测试操作符

常用的文件测试操作符有:

3. 逻辑操作符:

4. 正则表达比较操作符 (=~)

条件语句使用技巧

上一篇 下一篇

猜你喜欢

热点阅读