DEV Community

Nitin Namdev
Nitin Namdev

Posted on

Redirect shell command output

Shell scripts provide a very powerful feature: the ability to redirect the output from commands and scripts and send it to files, devices, or even as input to other commands or scripts.

Types of output
Commands and scripts in a shell can generate two basic types of outputs:

  1. STDOUT: The normal output from a command/script (file descriptor 1)
  2. STDERR: The error output from a command/script (file descriptor 2) By default, STDOUT and STDERR are sent to your terminal's screen.

Redirect STDOUT

For the following examples, I will use this simple set of files:

$ls -la file*
-rw-r--r--. 1 admin2 admin2  7 Mar 27 15:34 file1.txt
-rw-r--r--. 1 admin2 admin2 10 Mar 27 15:34 file2.txt
-rw-r--r--. 1 admin2 admin2 13 Mar 27 15:34 file3.txt
Enter fullscreen mode Exit fullscreen mode

I'm running a simple ls commands to illustrate STDOUT vs. STDERR, but the same principle applies to most of the commands you execute from a shell.

I can redirect the standard output to a file using ls file* > my_stdout.txt:

$ls file* > my_stdout.txt

$ cat my_stdout.txt 
file1.txt
file2.txt
file3.txt
Enter fullscreen mode Exit fullscreen mode

Next, I run a similar command, but with a 1 before >. Redirecting using the > signal is the same as using 1> to do so: I'm telling the shell to redirect the STDOUT to that file. If I omit the file descriptor, STDOUT is used by default. I can prove this by running the sdiff command to show the output of both commands side by side:

$ls file* 1> my_other_stdout.txt

$sdiff my_stdout.txt my_other_stdout.txt
file1.txt                        file1.txt
file2.txt                        file2.txt
file3.txt                        file3.txt
Enter fullscreen mode Exit fullscreen mode

Send STDOUT and STDERR to the same file

Another common situation is to send both STDOUT and STDERR to the same file:

$ls file* non-existing-file* > my_consolidated_output.txt 2>&1

$ cat my_consolidated_output.txt 
ls: cannot access 'non-existing-file*': No such file or directory
file1.txt
file2.txt
file3.txt
Enter fullscreen mode Exit fullscreen mode

In this example, all output (normal and error) is sent to the same file.

The 2>&1 construction means "send the STDERR to the same place you are sending the STDOUT."

Top comments (0)