仅当程序输出成功时,才如何对其进行重定向? [英] How to redirect output of a program only if it succeeded?

查看:38
本文介绍了仅当程序输出成功时,才如何对其进行重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的程序之一返回非零退出代码时,我想避免重定向其输出.这可能吗?如果可以,我该怎么做?

When one of my programs returns with a non-zero exit code, I want to avoid redirecting its output. Is this possible, and, if so, how do I do this?

我的尝试失败:

echo foo > file
false | cat > file

这将导致 file 为空.我想要的行为是仅在程序成功时调整 file .

this results in file being empty. The behaviour I want is to only adjust file when the program succeeds.

我还想知道是否有可能仅在输出为非空时更新文件,而不使用多个文件.

I also wonder whether it is possible do only update a file if the output is non-empty, without using multiple files.

推荐答案

您可以像这样使用它:

out=$(some_command) && echo "$out" > outfile

echo"$ out">仅当 some_command 成功时,outfile 才会执行.

echo "$out" > outfile will execute only when some_command succeeds.

这篇关于仅当程序输出成功时,才如何对其进行重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆