如果结构比较两个命令的结果

时间:2014-06-24 10:25:20

标签: bash if-statement

我想比较bash中两个命令的结果:

if `cat /root/pid` == `ps aux | grep "python" | grep -v grep | awk '{print $2}'`
then
   <SomeCommands>
else
   <OtherCommands>
fi

我想检查cat /root/pidps aux | grep "python" | grep -v grep | awk '{print $2}'的结果是否相等。

我还想检查我的服务器中是否正在运行特定的command。我认为这种方法有效。欢迎任何其他方法。

谢谢

3 个答案:

答案 0 :(得分:2)

您可以使用:

[[ "$(cat /root/pid)" == "$(ps aux | grep 'python' | grep -v grep | awk '{print $2}')" ]]

虽然我相信您可以减少grep并使用awk本身完成所有操作。

答案 1 :(得分:1)

if [[ "$(cat /root/pid)" == "$(ps aux | grep "python" | grep -v grep | awk '{print $2}')" ]]
then
<SomeCommands>
else
<OtherCommands>
fi

你的if命令在语法上是不正确的,因为它不包含[[ [((括号,也可能最好双重命令,以便将它们作为整个字符串读取< / p>

答案 2 :(得分:1)

你可以缩短它:

   if  [ "$(cat /root/pid)" == "$(pidof python)" ]; then
        <someCommands>
   else
        <otherCommands>
   fi