How can I redirect stderr to a file?

2019-09-21 03:52发布

问题:

What is the command required to redirect the standard error descriptor to a file called error.txt in unix?

I have this command so far:

find / -name "report*" ________ error.txt

回答1:

You can use the stderr handler 2 like this:

find / -name "report*" 2>error.txt

See an example:

$ ls a1 a2
ls: cannot access a2: No such file or directory  <--- this is stderr
a1                                               <--- this is stdin
$ ls a1 a2 2>error.txt
a1
$ cat error.txt 
ls: cannot access a2: No such file or directory  <--- just stderr was stored

As read in BASH Shell: How To Redirect stderr To stdout ( redirect stderr to a File ), these are the handlers:

Handle  Name    Description
0       stdin   Standard input   (stdin)
1       stdout  Standard output  (stdout)
2       stderr  Standard error   (stderr)

Note the difference with &>error.txt, that redirects both stdin and stderr (see Redirect stderr and stdout in a bash script or How to redirect both stdout and stderr to a file):

$ ls a1 a2 &>error.txt
$ cat error.txt 
ls: cannot access a2: No such file or directory  <--- stdin and stderr
a1                                               <--- were stored


标签: bash unix find