Arun Kumar
Arun Kumar

Reputation: 43

2>&1 is giving two ouptuts

I don't have any file called "new" and hence it is redirected to the test.txt(stedrr)

cat new 2> test.txt

But why I am getting 2 stderr output when I run the below command?

cat new 2>&1 test.txt
cat: new: No such file or directory
cat: new: No such file or directory

Upvotes: -1

Views: 142

Answers (1)

Stephen C
Stephen C

Reputation: 718658

This is what I get:

$ cat new 2>&1 test.txt
cat: new: No such file or directory
cat: test.txt: No such file or directory

Note that it complains about 2 different files.

Explanation.

The syntax for the cat command is:

cat [OPTION]... [FILE]...

In other words, it takes (potentially) multiple files and writes them to standard output. In the example above, the command is printing No such file or directory twice because you have given it 2 different input files that do not exist.

Wait? What? 2 input files?

Yes!!

In your command, 2>&1 means send standard error to the same place as standard output. But since you did not redirect standard output ... it goes to the console.

If you want both standard error and standard output to go to a file, you need to redirect standard output as well; e.g.

$ cat > new 2>&1 test.txt
$ cat new
cat: test.txt: No such file or directory
    

Now new will contain the error message that was written to standard error by cat!

Conversely, if you wanted the output and errors in test.txt it would be:

$ cat > test.txt 2>&1 new
$ cat test.txt
cat: new: No such file or directory

... or the contents of new ... if it existed.


So why did you get this?

$ cat new 2>&1 test.txt
cat: new: No such file or directory
cat: new: No such file or directory

Well my guess is that test.txt actually exists ... and that it contains

cat: new: No such file or directory

from the previous attempt:

$ cat new 2> test.txt

That writes (only!!) the errors to test.txt.

Upvotes: 1

Related Questions