oligofren
oligofren

Reputation: 22993

If redirecting STDERR to STDOUT and redirecting STDOUT to a file, why are STDERR messages not showing in the file?

I made a quick little script, test.sh, that looks like the following:

echo "StdErr" > /dev/stderr
echo "StdOut" > /dev/stdout

According to the answers to this SO question, and the Advanced Bash-Scripting Guide, the following should redirect stderr to stdout from the script above:

$ sh /tmp/test.sh 2>&1 

And indeed it does:

$ sh /tmp/test.sh 2>&1 |tee file;
$ cat file
StdErr
StdOut

The question that I am wondering is where does the output from stderr go in the following code?

$ sh /tmp/test.sh > file 2>&1
$ cat file
StdOut

I am using GNU bash, version 4.0.24(2)-release.

Upvotes: 1

Views: 1428

Answers (3)

Desislav Kamenov
Desislav Kamenov

Reputation: 1203

I have the same issue on RedHat with Bash version GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu). On my Mac with Bash and ZSH both works as expected.

[13:31:05][user@machine: ~/src]$ bash test
1STD ERR
2STD ERR
3STD OUT
4STD OUT
[13:31:40][user@machine: ~/src]$ bash test >> log 2>&1
[13:31:48][user@machine: ~/src]$ cat log 
4STD OUT
[13:31:52][user@machine: ~/src]$ 
[13:32:10][user@machine: ~/src]$ bash test > log 2>&1
[13:32:15][user@machine: ~/src]$ cat log 
4STD OUT
[13:32:18][user@machine: ~/src]$ 

Upvotes: 1

William Pursell
William Pursell

Reputation: 212584

Your script writes "StdErr" to the file. Then, the next line overwrites the file with "StdOut". You should use >> if you want to append to the file. Since you are redirecting, /dev/stderr and /dev/stdout are regular files, subject to truncation. Try your test again, but this time make file a fifo instead of a regular file.

Upvotes: 3

Fredrik
Fredrik

Reputation: 746

I'm seeing the output to stderr going to the file, as expected:

$> sh test.sh > file 2>&1
$> cat file 
StdErr
StdOut

This is bash 3.2.48.

$> bash --version
GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin11)

Upvotes: 2

Related Questions