[英]Bash - reuse the output in pipes if the first consumer fails
我的操作费用很高( curl
调用)。 这可能会或可能不会产生JSON。 如果是这样,我想使用json_pp
漂亮地打印它。 但是,如果失败,我想按原样打印。
这就是我现在所拥有的:
filter "$ENVI" "$2" running | dns_ \
| xargs -L1 --max-args=1 -I{} $DEBUG_XARGS --no-run-if-empty \
sh -c "echo 'Versions at {}': ; curl --fail http://... | json_pp"
相关部分是
curl --fail http://... | json_pp
当输出为JSON时,就可以了。 但是当不是的时候,我得到:
格式错误的JSON字符串,数组,对象,数字,字符串或原子都不是,位于/ usr / bin / json_pp第45行的字符偏移量0(“ Version:18.4.0,bui ...”之前)。
我想以某种方式对json_pp
的错误代码做出反应,以便如果它不为0
,则输出将在管道中进一步传递( cat
将接收它的位置),但是如果它返回0
(接受JSON),则管道不会继续(或继续json_pp
的输出)。
换句话说,我想跳过失败的管道中的步骤。
我该如何实现? 寻找类似的东西
curl --fail http://... | ifTheFollowingFailsThenPassAsIsOtherwiseUseOutputOf json_pp | cat
因为这一切都发生在xargs
,所以我正在寻找一个简短的解决方案,例如tee
。 它也可能是Bash函数。
tryOrCat() {
local input output
input=$(cat) || return
if output=$("$@" <<<"$input"); then
printf '%s\n' "$output"
else
printf '%s\n' "$input"
fi
}
...此后:
whatever | tryOrCat json_pp
这是我发布后一段时间想出来的:
bbTmp=$(mktemp "${TMPDIR:-/tmp}/bbPp.XXXXXX")
export bbTmp # to be available to sh -c
filter "$ENVI" "$2" running | dns_ | xargs -L1 --max-args=1 -I{} --no-run-if-empty \
sh -c 'curl --fail http://{}/... | tee "$bbTmp" | json_pp 2>/dev/null || cat "$bbTmp"'
就像我需要的那样。 感谢其他提示,对于更通用的解决方案将很有用。
管道中的输出只能处理一次。 您需要复制它或保存它。 后者很容易:
json=$(curl --fail http://...)
json_pp <<< "$json" || printf '%s\n' "$json"
这将使json_pp
的错误消息可见。 如果要隐藏它,可以重定向stderr:
json_pp <<< "$json" 2>/dev/null || printf '%s\n' "$json"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.