'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 1:[1]

Remember, the > operator replaces the existing contents of the file with the output of the command. If you want to save the output of multiple commands to a single file, you’d use the >> operator instead. This will append the output to the end of the file.

For example, the following command will append output information to the file you specify:

ls -l >> /path/to/file

So, for log the command output only if it success, you can try something like this:

until command
do
  command >> /path/to/file
done

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1