1. >
# Redirect stdout to a file.
# Creates the file if not present, otherwise overwrites it.
2. >>
# Redirect stdout to a file.
# Creates the file if not present, otherwise appends to it.
&>filename # Redirect both stdout and stderr to file "filename."
# This operator is now functional, as of Bash 4, final release.1>filename # Redirect stdout to file "filename."
1>>filename # Redirect and append stdout to file "filename."
2>filename # Redirect stderr to file "filename."
2>>filename # Redirect and append stderr to file "filename."
: > filename # Clear the file, create it if not present.
For example:
Write a script that upon invocation shows the time and date, lists all logged-in users, and gives the
system uptime. The script then saves this information to a logfile.
#!/bin/bash
LOGFILE=script.log
ERRORFILE=script.errors
date 1>$LOGFILE
logname 1>>$LOGFILE
uptime 1>>$LOGFILE
bad_command1 2>>$ERRORFILE
bad_command2 2>>$ERRORFILE
bad_command3
date &>$LOGFILE
logname &>>$LOGFILE
uptime &>>$LOGFILE
bad_command4 &>>$LOGFILE
# end of file
Note: ERRORFILE=script.errors # Right format.
ERRORFILE = script.errors # Wrong format! It will generate a error message.