Search code examples
bashshellcatoverwriteout

bash : cat commands output only if it success


I'm trying to redirect a command's output in a file only if the command has been successful because I don't want it to erase its content when it fails. (command is reading the file as input)

I'm currently using

cat <<< $( <command> ) > file;

Which erases the file if it fails.

It's possible to do what I want by storing the output in a temp file like that:

<command> > temp_file && cat temp_file > file

But it looks kinda messy to me, I want avoid manually creating temp files (I know <<< redirection is creating a temp file)

I finally came up with this trick

cat <<< $( <command> || cat file) > file;

Which will not change the contents of the file... but which is even more messy I guess.


Solution

  • Perhaps capture the output into a variable, and echo the variable into the file if the exit status is zero:

    output=$(command) && echo "$output" > file
    

    Testing

    $ out=$(bash -c 'echo good output') && echo "$out" > file
    $ cat file
    good output
    
    $ out=$(bash -c 'echo bad output; exit 1') && echo "$out" > file
    $ cat file
    good output