Department of Engineering

IT Services

Input/Output and Redirection

Unix processes have standard input, output and error channels. By default, standard input comes from the keyboard and standard output and error go to the screen, but redirecting is simple. Type


and the date will be shown on screen, but type

        date > out

and the output goes into the file called out.

        hostname >> out

will append hostname's output to the file out. stderr (where error message go) can also be redirected. Suppose you try to list a non-existent file (blah, say)

ls blah

You will get an error message `blah not found'. There's a file on all unix systems called /dev/null, which consumes all it's given. If you try

ls blah > /dev/null

you still wouldn't get rid of the error message because, not surprisingly, the message is being sent to stderr not stdout, but

ls blah 2>/dev/null

redirecting channel 2, stderr, will do the trick.

You can also redirect output into another process's input. This is done using the `|' character (often found above the <Return> key). Type `date | wc' and the output from date will be `piped' straight into a program that counts the number of lines, words and characters in its input. cat is a program that given a filename prints the file on-screen, so if you have a text-file called text you can do cat text | wc or wc < text instead of the usual wc text to count the contents of the file.

Standard output can also be `captured' and put in a variable. Typing


will set the variable d to be whatever string the command date produces. The use of $() to do this supercedes the use of backquotes (i.e. d=`date`) in older shells. $(<datafile) is a faster way of doing $(cat datafile) to put the contents of a file into a variable.

If you want to print lots of lines of text you could use many echo statements. Alternatively you could use a here document

Here is a line of text
and here is another line.

The cat command uses as its input the lines between the END words (any word could be used, but the words have to be the same).

If you want to read from a file a line at a time (or want to get input from the keyboard) use read. You can use one of the methods below - the second may be much the faster.

echo Reading /etc/motd using cat
cat /etc/motd | while  read line
  echo "$line"

echo Reading /etc/motd using exec redirection
exec 0</etc/motd
while read line
  echo "$line"