Classnotes | UNIX01 | RecentChanges | Preferences We have already seen that <<, <, |, >, and >> redirect and pipe the standard output (STDOUT) of a given program, command or script. However, what if we wish to redirect or pipe the standard error (STDERR)?
Redirecting and Piping the STDERR
When you execute commands, it is possible that an error could occur. You may give the wrong number of arguments, or some kind of system error could take place. When an error occurs, the system will issue an error message. Usually such error messages are displayed on the screen with the STDOUT. However, UNIX distinguishes between STDOUT and STDERR, so they are seperate and distinct data streams.
In the next example, the "cat" command is given the name of a file that does not exist:
$ cat notfile
cat : notfile not found
cat exits with an error. Because error messages are in a seperate data stream than the STDOUT, error messages will be printed to the screen even if you are redirecting STDOUT,
$ cat notfile > mydata
cat : notfile not found
To redirect the STDERR, you use the 2> option
$ cat notfile 2> myerror
$ cat myerror
cat : notfile not found
Likewise, you can append using 2>>
$ cat notfile1 2>> myerrors
$ cat notfile2 2>> myerrors
$ cat myerrors
cat : notfile1 not found
cat : notfile2 not found
The '1>' and '1>>' redirects stand for the STDOUT. So you can combine STDOUT and STDERR clauses on the same command line
$ cat somefile 1> mydata 2> myerror
However, what if you wanted both STDOUT and STDERR outputted to the same file? What if, in your output, you needed to know when errors occured with respect to STDOUT? You can do this with the >& redirect:
$ cat somefile >& mydata
NOTE: This "&" is flush with the redirect. If you do not have it flush, then the "&" will background the process (as we have seen before).
echo
The echo comand takes a parameter and echos it back to STDOUT. For example, the following code
echo Fred Flintstone and Barney Rubble
would echo back
Fred Flintstone and Barney Rubble
If you supply the "-n" option, the newline at the end of an echo is supressed. This is useful if you are using echo to supply a question and you want the user to enter information at the end of the line
echo -n "Please input your name: "
Recall that, because echo writes to STDOUT, it can be redirected
echo "$uname:$uid" > somefile
read
The read command reads in a value for a variable. It is used to allow a user to interactively input a value for a variable. The read command literally reads the next line in the STDIN (everything up to a newline character). For example, if we wanted to prompt the user for a filename, we could do it thusly
echo Please enter a filename:
read filename
echo "The filename you gave was $filename"