How to redirect the standard output and the standard error in Unix

Sometimes you need to redirect the standard output (stdout) and / or the standard error (stderr). > or 1> redirects the stdout and 2> redirects the stderr.

Watch Free Movies

1. Redirecting the stdout to file:
command 1> file
# ls /etc/grub.d/ > file

2. Redirecting the stderr to file:

command 2> file

3. Redirecting both the stderr and stdout to the same file:

There are a few ways to do this:

command &> file

command 1> file 2> file

command > file 2>&1

$ strace -e open ls /lib &> file

4. Redirecting the stderr and the stdout in different files: command > file.out 2> file.err

$ ls -l {a,b,c} > file.out 2> file.err

Also, redirecting the standart error to the standard output: command 2>&1

Also the input can be redirected with <. Redirecting the input is very usefull because you can put the input file at the beginning of the line, in order to easily modify your command (your grep, in this case):

< /etc/passwd grep razvan (is the same as grep razvan /etc/passwd)

Now, it is easily for me to press the up arrow and modify command to < /etc/passwd grep mike .

Scroll to Top