When doing:

CMD > file.out

if CMD fails (non-zero exit code), 'file.out' with be empty or incomplete.

I looking for a way to cleanup in case the CMD fails.

When CMD is run in a CRON job I would prefer for the directed output file to be deleted instead of leaving an empty/incomplete file behind.

My initial idea was:

if ! CMD > file.out; then rm file.out; fi

However it hides the CMD exit status, making it unsuitable. (especially for CRON)

  • Can anyone think a better solution ?
  • Is there some functionality in bash or sh that would allow this ?
  • I was hoping maybe there is some 'tee' like utility that could:
    • It would redirect STDOUT output to a file
    • If the command fails it would remove output file
    • In all case it would return the CMD exit code
  • I ended up doing a small script that calls CMD and that create a temporary file and then move it on success. It also has additional logic that was needed.
    – Alex
    Commented Mar 12, 2018 at 5:56

1 Answer 1


Your initial idea is good and could be expanded into

if ! CMD >file.out; then rm file.out; exit 1; fi

If you need to capture the specific exit status from CMD, then do that and exit with it later:

if ! CMD >file.out; then err="$?"; rm file.out; exit "$err"; fi

Note that you can't use exit "$?" since at that point, rm has modified $?.

tee will always create its output file, no matter if data is available to put into it, so you would have the same issue as you had from the start.

  • Thx for the input. Indeed that would work. I understand tee will always act this way. Just thought it could be nice to have another cmd that does exactly this... but it might be better to just use standard unix tool / rely on bash.
    – Alex
    Commented Mar 12, 2018 at 5:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .