1. Redirecting stdout and stderr
-
To redirect standard output to a file we can use the "
>" redirection operator.ls -l /usr/binls -l /usr/bin > ls-output.txtls -l ls-output.txtless ls-output.txt -
Let's try the same example with a directory that does not exist:
ls -l /bin/usrls -l /bin/usr > ls-output.txtlsdoes not send its error messages to standard output.ls -l ls-output.txtThe file has zero length.
less ls-output.txtThe redirection operator
>has erased the previous content of the file. In fact, if we ever need to truncate (erase the content of) a file, or to create a new empty file, we can use a trick like this:> ls-output.txt -
To actually append the redirected output to the existing content of the file, instead of overwriting it, we can use the operator "
>>":ls -l /usr/bin >> ls-output.txtls -lh ls-output.txtls -l /usr/bin >> ls-output.txtls -lh ls-output.txtls -l /usr/bin >> ls-output.txtls -lh ls-output.txtNotice that the size of the file is growing each time.
-
To redirect stderr we can use the operators "
2>" and "2>>". In Linux, the standard output has the file descriptor (file stream number) 1, and the standard error has the file descriptor 2. So, hopefully this syntax makes sense to you and is similar to that of redirecting stdout.ls -l /bin/usr 2> ls-error.txtls -l ls-error.txtless ls-error.txt -
We can redirect both stdout and stderr to the same file, like this:
ls -l /bin/usr > ls-output.txt 2>&1The redirection
2>&1redirects the file descriptor2(stderr) to the file descriptor1(stdout). But before that we redirected the stdout tols-output.txt, so both stdout and stderr will be directed to this file.Notice that the order of the redirections is significant. Let's try it like this:
ls -l /bin/usr 2>&1 >ls-output.txtIn this case we redirect file descriptor
2(stderr) to file descriptor1, which is already the screen, and then we redirect the file descriptor1(stdout) to the file. So, the error messages will still be sent to the screen and not to the file.A shortcut for redirecting both stdout and stderr to the same file is using "
&>":ls -l /bin/usr &> ls-output.txtFor appending to the file we can use "
&>>":ls -l /bin/usr &>> ls-output.txtls -lh ls-output.txtls -l /bin/usr &>> ls-output.txtls -lh ls-output.txt -
To throw away the output or the error messages of a command, we can send them to
/dev/null:ls -l /bin/usr 2> /dev/null