Home > Software design >  2>&1 is giving two ouptuts
2>&1 is giving two ouptuts

Time:01-13

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

CodePudding user response:

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
    

Of course, now new contains the error message that was written to standard error by cat!


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.

  • Related