测试涉及管道的命令是否成功

Testing the Success of a Command Involving Pipes

在以下命令中测试 df 和 awk 命令是否成功的最佳方法是什么?使用 Solaris。

df -h /myloc* | awk '{ if ( > 80 ) print }' > somelog

一种简单的方法是将它们拆分,这样您就可以存储第一个输出并检查两个退出状态的结合:

if OUT1=$(df -h /myloc*) && echo ${OUT1} | awk '{ if (  > 80 ) print }' > somelog; then
  echo "success"
else 
  echo "failure"
fi

您应该使用 pipefail 选项(它在 ksh 中也受支持,在 Solaris 上默认为 shell):

$ if false | true; then echo ok; else echo failed; fi
ok
$ set -o pipefail
$ if false | true; then echo ok; else echo failed; fi
failed

您可以将该选项本地化为子shell:

if (set -o pipefail; false | true); then echo ok; else echo failed; fi

(将 falsetrue 替换为您各自的命令)