Free Hosting Online for WorkStations

< Previous | Contents | Next >

Redirecting Standard Output And Standard Error To One File

There are cases in which we may wish to capture all of the output of a command to a sin- gle file. To do this, we must redirect both standard output and standard error at the same time. There are two ways to do this. First, the traditional way, which works with old ver - sions of the shell:



[me@linuxbox ~]$ ls -l /bin/usr > ls-output.txt 2>&1

[me@linuxbox ~]$ ls -l /bin/usr > ls-output.txt 2>&1


Using this method, we perform two redirections. First we redirect standard output to the file ls-output.txt and then we redirect file descriptor 2 (standard error) to file de- scriptor one (standard output) using the notation 2>&1.


Notice that the order of the redirections is significant. The redirection of stan- dard error must always occur after redirecting standard output or it doesn't work. In the example above,


>ls-output.txt 2>&1


redirects standard error to the file ls-output.txt, but if the order is changed to


2>&1 >ls-output.txt


standard error is directed to the screen.


Recent versions of bash provide a second, more streamlined method for performing this

Redirecting Standard Error


combined redirection:



[me@linuxbox ~]$ ls -l /bin/usr &> ls-output.txt

[me@linuxbox ~]$ ls -l /bin/usr &> ls-output.txt


In this example, we use the single notation &> to redirect both standard output and stan- dard error to the file ls-output.txt. You may also append the standard output and standard error streams to a single file like so:



[me@linuxbox ~]$ ls -l /bin/usr &>> ls-output.txt

[me@linuxbox ~]$ ls -l /bin/usr &>> ls-output.txt


Top OS Cloud Computing at OnWorks: