在bash中替换太多if语句

时间:2018-01-25 06:52:25

标签: linux bash service sh rhel

我编写了一个bash脚本,其工作原理如下

1) Check for status of service1. If it is not started then check for status of service2. If service2 is not started then display error.
2) If service1 is started then check for log file of service1 and grep for `starting`. If it matches then success
3) If service2 is started then check for log file of service1 and grep for `starting`. If it matches then success

我的bash脚本如下所示,但if语句太多了。我试图想要减少这些if语句

#!/bin/bash
service service1 status | grep "good" > /dev/null
if [ $? -ne 0 ];then
    service service2 status | grep "good" > /dev/null
    if [$? -ne 0];then
        var1="service1 is down"
        echo "$var1"
    else
        cat /dir/log2 | grep "abc" > /dev/null 2>&1
        if [ $? -ne 0 ];then
            var2="exception"
            echo "$var2"
        fi
    fi
else
    cat /dir/log1 | grep "abc" > /dev/null 2>&1
    if [ $? -ne 0 ];then
        var3="exception"
        echo "$var3"
    fi
fi

2 个答案:

答案 0 :(得分:1)

您可以在bash中使用 case 语句来避免多级if-else语句。

关注blog可能会对此有所帮助。

答案 1 :(得分:0)

我对你要测试的确切逻辑感到有点困惑 - 描述与下面的代码不完全匹配。我怀疑问题的一部分是进行负面测试(即如果未找到,那么......)可能会令人困惑。因此,例如,描述说“如果[Starting]匹配然后成功”,但代码执行“如果abc 匹配则varN = exception”。此外,如果service2正在运行,它会检查log1,如果service1正在运行,则检查log2。我建议切换到正面测试(例如,如果找到了 的内容,那么......),并添加注释以跟踪在什么条件下运行的代码。

测试本身也有一些简化。 somecommand; if [ $? -ne 0 ]; then(否定测试 - 如果命令失败则运行)可以替换为if ! somecommand; then(或if somecommand; then替换为正测试版本)。此外,grep something >/dev/null可以替换为grep -q something(其优点是它不扫描整个文件,它会在第一次匹配时停止),cat somefile | grep something可以替换为grep something somefile 1}}(保存流程并提高效率)。

将测试切换为正面形式并进行上述简化,并使我认为必要的更正得出:

#!/bin/bash

if service service1 status | grep -q "good"; then
    # This section executes if service1 is "good"
    if grep -q "abc" /dir/log1 2>/dev/null; then
        # service1 is "good" and /dir/log1 contains "abc"
        # Should there be something executable here? If not, add "!"
        # after the "if", and swap the "else" section here
        : success
    else
        # service1 is "good" and /dir/log1 does not contain "abc"
        # Is this where the "exception" stuff actually belongs?
        var3="exception"
        echo "$var3"
    fi

elif service service2 status | grep "good"; then
    # This section executes if service1 is not "good", but service2 is
    if grep -q "abc" /dir/log2 2>/dev/null; then
        # service2 is "good" and /dir/log2 contains "abc"
        : success
    else
        # service1 is "good" and /dir/log2 does not contain "abc"
        # Again, is this where the "exception" stuff actually belongs?
       var2="exception"
        echo "$var2"
    fi

else
    # Neither service1 nor service2 is "good"
    var1="service1 is down"
    echo "$var1"

fi