Skip to main content

Shell, Bash, and other modern shell provides I/O redirection facility. Here's examples of redirecting the standard error stream to a file.

# -----------------------------------------------------------------------------
# BASH Shell: How To Redirect stderr To stdout ( redirect stderr to a File )
#   http://www.cyberciti.biz/faq/redirecting-stderr-to-stdout/
# -----------------------------------------------------------------------------

##
# Redirecting the standard error stream to a file
#
# The following will redirect program error message to a file called error.log:
##
program-name 2> error.log
command1 2> error.log

# Redirecting the standard error (stderr) and stdout to file
command-name &>file
command > file-name 2>&1

find /usr/home -name .profile 2>&1 | more

# Redirect stderr to stdout
command-name 2>&1

##
# Consider the following example from the exit status chapter. The output of
# grep "^$username" $PASSWD_FILE > /dev/null is send to /dev/null where it is
# ignored by the shell.
#
# http://bash.cyberciti.biz/guide//dev/null_discards_unwanted_output
##

#!/bin/bash
# set var
PASSWD_FILE=/etc/passwd

# get user name
read -p "Enter a user name : " username

# try to locate username in in /etc/passwd
grep "^$username" $PASSWD_FILE > /dev/null

# store exit status of grep
# if found grep will return 0 exit stauts
# if not found, grep will return a nonzero exit stauts
status=$?

if test $status -eq 0
then
  echo "User '$username' found in $PASSWD_FILE file."
else
  echo "User '$username' not found in $PASSWD_FILE file."
fi