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

问题描述 投票:1回答:2

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

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

shell scripting pipe solaris
2个回答
0
投票

一种简单的方法是将它们拆分,以便您可以存储第一个输出并检查两个退出状态的相加:

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

0
投票

您应使用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

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

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

(用各自的命令替换falsetrue

© www.soinside.com 2019 - 2024. All rights reserved.