Home > Software design >  bash : cat commands output only if it success
bash : cat commands output only if it success

Time:05-20

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.

CodePudding user response:

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

CodePudding user response:

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
  • Related