[英]Bash: Capturing the output from a command and conditionally processing it
有没有更好的方式来处理的条件处理输出以下标准上下的方式吗?
output="$(program | grep -E 'some text')"
if [ ! -z "$output" ]; then
echo "$output" | mail -s 'captured output' to
fi
我在想一些明显错误的方法
program | grep -E 'some text' | { [[ $? == 0 ]] && mail -s 'captured output' to; }
有一种方法可以不必捕获输出。 在某些情况下(即巨大的产出),这可能是更可取的。 这样的东西,可以很容易地重用:
execute_on_input()
{
local c=
local r=0
IFS= read -r -n 1 c || r=$?
[[ "$c" ]] || return 0
{ echo -n "$c" ; [[ $r != 0 ]] || cat ; } | "$@"
}
program | grep -E 'some text' | execute_on_input mail -s 'captured output'
该函数检查是否可以读取某些内容,如果不能读取,则不启动位置参数中传递的命令(“ $ @”)。 如果找到了输出,则将其通过管道传递给位置参数中接收到的命令(首先读取第一个字符,然后使用cat
读取第一个read
未读取的其余部分)。
grep
的退出状态将告诉您是否存在匹配项。
if output=$(program | grep -E 'some text'); then
printf '%s' "$output" | mail -s 'captured output' to
fi
但是, mail
(至少是我正在查看的版本)具有-E
选项,该选项可防止发送空消息,从而无需进行检查。
program | grep -E 'some text' | mail -E -s 'captured output' to
您可以替换if [ ! -z "$output" ]
if [ ! -z "$output" ]
和if [ -n "$output" ]
(或if [ -n "${output}" ]
)。 其他可能性也一样,那么为什么使阅读变得更困难呢?
明确使用test
将显示您在做什么:
test -n "${output}" && echo "output filled"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.