How to redirect output of a program only if it succeeded?

南笙酒味 提交于 2020-01-14 02:18:13

问题


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?

My failed attempt:

echo foo > file
false | cat > 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.


回答1:


You can use it like this:

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

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




回答2:


if avoiding empty file creation and deletion is not essential, maybe it is a good replacement

false > file || rm -f file


来源:https://stackoverflow.com/questions/31424456/how-to-redirect-output-of-a-program-only-if-it-succeeded

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!