Pipes
An extension of redirecting input and output to and from files
is to redirect to and from other commands. The syntax for
pipes is similar to that for file redirection,
except that the symbol | (vertical bar) is used
instead of <</code> and >. If we have a
command X whose standard output is to be used as the
standard input to a command Y , we could have
$ X > tempfile
$ Y < tempfile
storing the output of X in a temporary file
tempfile . However, this is not elegant, and in some
situations impossible (if you require Y to process the
output of X as soon as it is produced). By means of a
pipe, we can join the two streams together, as follows:
$ X | Y
Worked example
Send an email message to user sam to inform
sam of the current time and date.
Solution: The command date sends to
its standard output the time and date, and mailx sends
an email message from the standard input stream. Therefore we can
pipe the output of date to the input of
mailx :
$ date | mailx -s "Today's time and date"
sam
Using > or <</code>, different
input or output streams can be specified, but pipes only connect
standard output to standard input, and cannot be used with the
standard error stream. You can use write in a script, and
since the input is standard input this can be redirected or piped
just as with any other UNIX command. However, you cannot use
talk in a pipe since it does not use the standard
input and output mechanisms. A script may contain input and output
redirection, and pipes.
Worked example
In a script, mail sam a message that says
Running my script now .
Solution: Using Vi, create a file containing:
echo Running my script now | mailx -s "What I'm doing"
sam
|