Bash在for循环中的if语句中退出

时间:2020-02-20 08:19:25

标签: linux bash loops

我正在尝试在Bash中执行for循环并在if语句上退出,但我意识到它将在完成循环之前破坏代码。

#!/bin/bash

for node in $(ps -ef | awk <something>);
do

  var=<command>
  echo "node ${node}"

  if [[ ${var} -gt 300000 ]]; then
    echo "WARNING!";
    exit 1;

  elif [[ ${var} -gt 1000000 ]]; then
    echo "CRITICAL!";
    exit 2;

  else
    echo "OK!";
    exit 0;
  fi
done

我的第二个选择是在循环外设置一个变量,而不是exit,但后来我意识到它将覆盖每个节点的状态:

#!/bin/bash

for node in $(ps -ef | awk <command>);
do

  var=<command>
  echo "node ${node}"

  if [[ ${var} -gt 300000 ]]; then
    echo "WARNING!";
    status="warning"

  elif [[ ${var} -gt 1000000 ]]; then
    echo "CRITICAL!";
    status="critical"

  else
    echo "OK!";
    status="ok"
  fi
done

if [[ status == "warning" ]]; then 
  exit 1;
elif [[ status == "critical" ]]; then 
  exit 2;
elif [[ status == "ok" ]]; then 
  exit 0;
fi 

如何在每个节点上正确退出?

2 个答案:

答案 0 :(得分:1)

这是另一种选择。它计算结果并根据计数器创建退出状态。我更改了语义,因为您的脚本永远不会到达CRITICAL路径。而是为值> 1000000输入了警告路径:

#!/bin/bash

let ok_count=0 warn_count=0 critical_count=0

for node in $(ps -ef | awk <command>);
do

  var=<command>
  echo "node ${node}"

  # >1000000 must be checked before >300000
  if [[ ${var} -gt 1000000 ]]; then
    echo "CRITICAL!";
    let critical_count++

  elif [[ ${var} -gt 300000 ]]; then
    echo "WARNING!";
    let warn_count++

  else
    echo "OK!";
    let ok_count++
  fi
done

if ((critical_count)); then 
  exit 2
elif ((warn_count)); then 
  exit 1
else
  exit 0
fi

如果仅需要退出状态,则可以优化此脚本: 严重是最高警告级别。因此计数是没有必要的。 确定是后备。因此,计数是不必要的。

#!/bin/bash

let warn_count=0

for node in $(ps -ef | awk <command>);
do

  var=<command>
  echo "node ${node}"

  if [[ ${var} -gt 1000000 ]]; then
    echo "CRITICAL! -> abort";
    exit 2 # no more analysis needed!

  elif [[ ${var} -gt 300000 ]]; then
    echo "WARNING!";
    let warn_count++
  fi
done

exit $(( warn_count > 0 ))

答案 1 :(得分:0)

使用continue运算符,来自man bash

...
       continue [n]
              Resume the next iteration of the enclosing for, while, until, or select loop.  If n is specified, resume at the nth enclosing loop.  n must be
              ≥ 1.  If n is greater than the number of enclosing loops, the last enclosing loop (the ``top-level'' loop) is resumed.  The return value is  0
              unless n is not greater than or equal to 1.

或者break,如果您需要退出循环

...
       break [n]
              Exit  from within a for, while, until, or select loop.  If n is specified, break n levels.  n must be ≥ 1.  If n is greater than the number of
              enclosing loops, all enclosing loops are exited.  The return value is 0 unless n is not greater than or equal to 1.