stdin, stderr, redirection and logs

Is there a difference between those two lines ?

/home/user/script.sh >> /home/user/stdout_and_error.log  2>&1
/home/user/script.sh 2>&1 >> /home/user/stdout_and_error.log

knowing that I would like to put the stdout and execution errors of the script in the log file.
If there are no differences, what if I would like to log the logging itself?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Yes, there is a difference.

/home/user/script.sh >> /home/user/stdout_and_error.log  2>&1

This will send both STDOUT and STDERR to /home/user/stdout_and_error.log.

/home/user/script.sh 2>&1 >> /home/user/stdout_and_error.log

This will send STDOUT to /home/user/stdout_and_error.log, and STDERR to what was previously STDOUT.

 

When you perform a shell redirection, the left side of the redirection goes to where the right side of the redirection currently goes. Meaning in 2>&1, it sends STDERR (2) to wherever STDOUT (1) currently goes.
But if you afterwards redirect STDOUT somewhere else, STDERR doesn’t go with it. It continues to go wherever STDOUT was previously going. This is why in your first example, both STDOUT and STDERR will go to the same place, but in the second they won’t.

Method 2

On the first command line, the shell sees >> file first and append stdout to file . Next 2>&1 sends fd2 ( stderr ) to the same place fd1 is going – that’s to the file. And that’s what you want.

On the second command line, the shell sees 2>&1 first. That means “make the standard error (file descriptor 2) go to the same place as the standard output (fd1) is going.” There’s no effect because both fd2 and fd1 are already going to the terminal. Then >> file appends fd1 ( stdout ) to file . But fd2 ( stderr ) is still going to the terminal.

Method 3

>> Appending stdout (stream #1) to a file.

2>&1 Combining stderr (stream #2) with stdout (stream #1) (Adds stderr into stdout)

> Writes stdout (stream #1) to a file, overwriting the file.

1> Writes stdout (stream #1) to a file, overwriting the file. Same as above.

2>Writes stderr (stream #2) to a file, overwriting the file.

+++

You’re first example would append stdout to a file, then add stderr to stdout.

You’re second example would add stderr to stdout, then append the combined stdout (with stderr included) to a file.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x