Search code examples
bashcygwin

Why can't I redirect stderr from within a bash -c command line?


I'm trying to log the time for the execution of a command, so I'm doing that by using the builtin time command in bash. I also wish to redirect the stderr and stdout to a logfile at the same time. However, it doesn't seem to be working as the stderr just spills out onto my terminal.

Here is the command:

rm -rf doxygen
mkdir doxygen
bash -c 'time "/cygdrive/d/Program Files/doxygen/bin/doxygen.exe" Doxyfile > doxygen/doxygen.log 1>&2' genfile > doxygen/time 1>&2 &

What am I doing wrong here?


Solution

  • You are using 1>&2 instead of 2>&1.

    With the lengths of names reduced, you're trying to run:

    bash -c 'time doxygen Doxyfile > doxygen.log 1>&2' genfile > doxygen.time 1>&2 &
    

    The > doxygen.log sends standard output to the file; the 1>&2 then changes your mind and sends standard output to the same place that standard error is going. Similarly with the outer pair of redirections.

    If you used:

    bash -c 'time doxygen Doxyfile > doxygen.log 2>&1' genfile > doxygen.time 2>&1 &
    

    then you send standard error to the same place that standard output goes — twice.

    Incidentally, do you realize that the genfile serves as the $0 for the script run by bash -c '…'? I'm not convinced it is needed in your script. To see this, try:

    bash -c 'echo 0=$0; echo 1=$1; echo 2=$2' genfile jarre oxygene
    

    When run, this produces:

    0=genfile
    1=jarre
    2=oxygene