Search code examples
cbashcsh

Is there a way to redirect stderr to a file that works in bash, csh and dash?


How do I redirect stderr (or stdout+stderr) to a file if I don't know which shell (bash, csh, dash) is interpreting my command?

My C code running on Linux/FreeBSD/OSX needs to call an external program via the system() function, which will use /bin/sh to interpret the supplied command line. I would like to capture the messages printed by that external program to stderr and save them to a file. The problem is that on different systems /bin/sh points to different shells that have different syntax for redirecting the stderr stream to a file.

The closest thing I found is that bash actually understands the csh-style syntax for redirecting stderr+stdout to a file:

some_program >& output.txt

but dash, which is the default shell on Ubuntu (i.e. very common), does not understand this syntax.

Is there a syntax for stderr redirection that would be correctly interpreted by all common shells? Alternatively, is there a way to tell system() (or some other similar C function?) to use /usr/bin/env bash instead of /bin/sh to interpret the supplied command line?


Solution

  • On any POSIX-like system, you can use

    system("some_program > output.txt 2>&1");
    

    This is because POSIX system is equivalent to calling sh, and POSIX sh supports this kind of redirection. This works independently of whether or not a user opening a terminal on the system will see a Csh prompt.