Bash and other modern shell provides I/O redirection facility. There are 3 default standard files (standard streams) open:
[a] stdin - Use to get input (keyboard) i.e. data going into a program.
[b] stdout - Use to write information (screen)
[c] stderr - Use to write error message (screen)
[a] stdin - Use to get input (keyboard) i.e. data going into a program.
[b] stdout - Use to write information (screen)
[c] stderr - Use to write error message (screen)
Understanding I/O streams numbers
The Unix / Linux standard I/O streams with numbers:Handle | Name | Description |
0 | stdin | Standard input |
1 | stdout | Standard output |
2 | stderr | Standard error |
$cat food 2>&1 >file
cat: can't open food $cat food >file 2>&1
$
- On the first 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
redirects fd1 ( stdout ) tofile
. But fd2 ( stderr ) is still going to the terminal. - On the second command line, the shell sees
>file
first and redirects stdout tofile
. Next2>&1
sends fd2 ( stderr ) to the same place fd1 is going - that's to the file. And that's what you want.