如果管道输出为空,则生成其他退出行为

时间:2018-12-08 20:02:31

标签: bash

我有一个bash shell脚本在做某事

#!/bin/bash
# construct regex from input
# set FILE according to input file
egrep "${regex}" "${FILE}" | doing stuff | sort

如果要找到匹配项(它正在执行),我希望此脚本将命令的输出(用新行分隔的匹配项列表)写入stdout。如果没有找到匹配项,则需要向stderr写一条错误消息,并以退出状态3退出。

我尝试过

#!/bin/bash
# construct regex from input
# set FILE according to input file
function check () {
  if ! read > /dev/null
    then
      echo "error message" 1>&2
      exit 3
  fi
}
egrep "${regex}" "${FILE}" | doing stuff |
sort | tee >(check)

现在已写出正确的错误消息,但退出状态为“无法逃脱子外壳程序”;外部脚本仍以退出状态0退出。

我也尝试过某事

#!/bin/bash
# construct regex from input
# set FILE according to input file
if ! egrep "${regex}" "${FILE}" | doing stuff | sort
then
  echo "error message" 1>&2
  exit 3
fi

但是这里我有一个问题,管道中的命令之一(尤其是sort)以退出状态0退出

我如何获得所需的退出状态3和错误消息,同时保持输出正常执行,而又不做所有所有工作两次?

编辑: 我可以通过使用

来解决问题
#!/bin/bash
# construct regex from input
# set FILE according to input file
if ! egrep "${regex}" "${FILE}" | doing stuff | sort | grep . 
then
  echo "error message" 1>&2
  exit 3
fi

但是我不确定这是最好的方法,因为管道是并行工作的...

1 个答案:

答案 0 :(得分:1)

我将使用PIPESTATUS检查egrep的退出代码:

#!/bin/bash
# construct regex from input
# set FILE according to input file
egrep "${regex}" "${FILE}" | doing stuff | sort
if [[ ${PIPESTATUS[0] != 0 ]]; then
  echo "error message" 1>&2
  exit 3
fi

某些上下文:

$ {PIPESTATUS [@]} 只是一个数组,其中包含您所链接的每个程序的退出代码。 $?只会为您提供管道中最后一条命令的退出代码。