Search code examples
bashstdoutstderr

Redirect STDOUT to STDERR when exit status isn't 0 in Bash


The programming language Crystal currently doesn't write to STDERR when there's a compile time failure. I need to redirect STDOUT to STDERR if the exit status is not 0 and still return the exit status.


Solution

  • Taken literally, your request is literally impossible: Redirections are performed before a command has started, whereas exit status is only known when it exits.

    However, you can unconditionally redirect into a buffer, and then write that buffer to either stdout or stderr after exit status is known.

    Consider a wrapper akin to the following:

    #!/bin/sh
    if output=$("$@"); then
      printf '%s\n' "$output"
    else
      retval=$?
      printf '%s\n' "$output" >&2
      exit "$retval"
    fi
    

    ...invoked as (if this is saved as stderr-wrapper):

    stderr-wrapper your-program arg1 arg2 ...