12

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.

Jonny5
  • 1,390
  • 1
  • 15
  • 41

2 Answers2

16

You can use it like this:

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

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

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • is it also possible to check for empty output in a similar way? What is the difference between `$(...)` and `\`...\``? – Jonny5 Jul 15 '15 at 08:03
  • 1
    `$(...)` is newer and preferred way of command substitution. We can check non-empty value as well like: **`out=$(some_command) && [[ -n "$out" ]] && echo "$out" > outfile`** – anubhava Jul 15 '15 at 08:05
  • 2
    Note: If the output of some_command is huge, you may want to `t=$(mktemp); some_command >$t && cat $t > outfile; rm -f $t` – anishsane Jul 15 '15 at 10:19
  • Yes `mktemp` is the way to go for handling huge output. – anubhava Jul 15 '15 at 10:21
  • 2
    And just to scope the issue a bit, shell redirection and pipes happen before your command is even run. This is why your original attempts couldn't work; your output file was gone before your program ever ran. – Erik Bennett Jul 15 '15 at 16:37
  • 2
    I am continuously amazed at how poorly designed shell scripting is – Andy Ray May 18 '20 at 23:09
  • 1
    NB: double quotes in echo "$out" are mandatory if output contains newlines – Marco Marsala Jan 06 '21 at 17:41
0

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

false > file || rm -f file
William Leung
  • 1,556
  • 17
  • 26