Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

unix

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.

like image 616
Jonny5 Avatar asked Jul 15 '15 07:07

Jonny5


1 Answers

You can use it like this:

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

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

like image 150
anubhava Avatar answered Oct 19 '22 01:10

anubhava