2

If 2>&1 redirects the stderr to the stdout, isn't that what just '>' does? So does '2>&1' and '>' have the same meaning or are they different in some way? Explanations about redirections seem to revolve around the difference between what each of them mean but does not say if '2>&1' and '>' are the same. Can someone tell me where i am wrong ?

2 Answers 2

5

> has a meaning on its own. It is a redirection operator.

2> may be redirecting stderr, but stderr is not the only output from a task. There is also stdout which is 1 and there are also other places you could redirect to.

For example >myOutput.txt will redirect output (I believe only stdout by default) from that task to your file.

Then there is 1>stdOut.txt which explicitly redirects only stdout to the output file.

By extension you could also do 2>stdErr.txt

The reason to do 2>&1 is to redirect stderr to the same stream as stdout so that you only have one stream as an output from the command. Then that combined output can be redirected as one command.

So rather than

myCommand 1>stdOut.txt 2>stdErr.txt

You can do

myCommand 1>combinedOut.txt  2>&1 
2
  • Thanks man. Before asking the question I printed out the output into the terminal in which case both seemed to have the same answer. Now i tried writing to a file with the > and the 2>&1 and it is very different. Oct 6, 2021 at 11:54
  • @randomSapien yep, by default both stderr and stdout will go to your console so it will look the same, it's when you need to actually send that output somewhere that you find out that they are not the same.
    – Mokubai
    Oct 6, 2021 at 12:08
1

So rather than

myCommand 1>stdOut.txt 2>stdErr.txt

You can do

myCommand 2>&1 1>combinedOut.txt

… it is not really correct… if you want to send stderr and stdout at the same place, the 2>&1 has to be used at the end of the command.

Here, the stderr is sent at your stdout not redirected (console), and the stdout is sent to the file with no effect on the stderr.

1
  • Okay, thanks man. For anyone wondering i got the result using command > file.txt 2>&1 Oct 7, 2021 at 0:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .