我写了一个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

最佳答案

可以在bash中使用case语句来避免使用多个级别的if-else语句。
以下blog可能有助于您了解这一点。

关于linux - 在bash中替换过多的if语句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48437162/

10-14 15:59
查看更多