System Edge | blog by dmars

Output redirection in bash shell

Date: Jan 12 2012 | Tags: output redirection, bash, Unix, Linux

In Unix, there are three standard streams: one input stream, STDIN; and two output streams, STDOUT and STDERR.

The operators to redirect the output to a file are '>' for overwrite and '>>' for append. Of course, a stream can be redirected to another stream. Here are some examples.

echo command prints arguments to STDOUT. It can be redirected to a file called hello.txt using the following command.

$ echo "hello." > hello.txt

This will create or overwrite hello.txt (if permissions allow).

To append a text, use '>>' operator.

$ echo "another hello." >> hello.txt

The contents of the file are now:

$ cat hello.txt
hello.
another hello.

When we use '>' and '>>' operators as shown above, we are redirecting a default output stream, STDOUT. To explicitly redirect STDOUT stream, we can use its file descriptor, which is '1', like this:

echo "hello." 1> hello.txt

Errors are sent to STDERR stream, which default to screen. STDERR file descriptor has a value of 2. So, to log errors in a file, look at this example where the file name does not exist:

$ cat nofile.txt 2> errors.log
$ cat errors.log
cat: 0652-050 Cannot open nofile.txt.

Both streams can be redirected in the same command. Here are few variants that will send all output into nothing:

/home/dmars/batch.sh 1> /dev/null 2> /dev/null
/home/dmars/batch.sh &> /dev/null
/home/dmars/batch.sh 1> /dev/null 2>&1

Output redirection can be done in shell scripts in one place by using exec command. exec will modify file descriptors when no command-line arguments are passed. So, to redirect both output file streams to a file from inside the script, look at the following example:

#!/bin/bash

# Redirect STDOUT and STDERR
exec 1> results.txt
exec 2> errors.txt

# Set some parameters
export USEFUL_PARAM1="VALUE"
export USEFUL_PARAM2="$VARIABLE"

# Do something useful
exec ./useful.sh

What do you think?




0 comments