Jonny5
Jonny5

Reputation: 1499

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

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.

Upvotes: 18

Views: 7777

Answers (2)

William Leung
William Leung

Reputation: 1653

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

false > file || rm -f file

Upvotes: 1

anubhava
anubhava

Reputation: 785176

You can use it like this:

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

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

Upvotes: 21

Related Questions