Softpanorama
(slightly skeptical) Open Source Software Educational Society

May the source be with you, but remember the KISS principle ;-)

Google   


Shell Input and Output Redirection

News

See also

Best Shell Books

Recommended Links Papers, ebooks  tutorials

Pipes

Reference
Pipes in Loops Process Substitution in Shell Tee   Tips Humor Etc
Before shell executes a command, it scans the command line for redirection characters. These special notations direct the shell to redirect input and output. Redirection characters can appear anywhere in a simple command or can precede or follow a command. They are not passed on to the invoked command.

The shell performs command and parameter substitution before using the Word or Digit parameter except as noted. File name substitution occurs only if the pattern matches a single file and blank interpretation is not performed. There are several cases:

  1. <Source   Uses the file specified by the Source    as standard input (file descriptor 0).
  2. >Target Uses the file specified by the target  as standard output (file descriptor 1). If the file does not exist, the shell creates it. If the file exists and the noclobber option is on, an error results; otherwise, the file is truncated to zero length.
    • Note: When multiple shells have the noclobber option set and they redirect output to the same file, there could be a race condition, which might result in more than one of these shell processes writing to the file. The shell does not detect or prevent such race conditions.
  3. >>Target  Uses the file specified by target  as standard output. If the file currently exists, the shell appends the output to it (by first seeking the end-of-file character). If the file does not exist, the shell creates it.
     
  4. <>Stream Opens the file specified by the Word parameter for reading and writing as standard input.
  5. <<[-] Source Reads each line of shell input until it locates a line containing only the value of the Word parameter or an end-of-file character. The shell does not perform parameter substitution, command substitution, or file name substitution on the file specified. The resulting document, called a here document, becomes the standard input. If any character of the Word parameter is quoted, no interpretation is placed upon the characters of the document. The here document is treated as a single word that begins after the next newline character and continues until there is a line containing only the delimiter, with no trailing blank characters. Then the next here document, if any, starts. The format is as follows:
[n]<<word
   here document
delimiter

 

If any character in word is quoted, the delimiter is formed by removing the quote on word. The here document lines will not be expanded. Otherwise, the delimiter is the word itself. If no characters in word are quoted, all lines of the here document will be expanded for parameter expansion, command substitution, and arithmetic expansion.

The shell performs parameter substitution for the redirected data. To prevent the shell from interpreting the \, $, and single quotation mark (') characters and the first character of the Word parameter, precede the characters with a \ character.

If a hyphen (-) is appended to <<, the shell strips all leading tabs from the Word parameter and the document.

<&Digit Duplicates standard input from the file descriptor specified by the Digit parameter
>& Digit Duplicates standard output in the file descriptor specified by the Digit parameter
<&- Closes standard input
>&- Closes standard output
<&p Moves input from the co-process to standard input
>&p Moves output to the co-process to standard output
If one of these redirection options is preceded by a digit, then the file descriptor number referred to is specified by the digit (instead of the default 0 or 1). In the following example, the shell opens file descriptor 2 for writing as a duplicate of file descriptor 1:
... 2>&1
The order in which redirections are specified is significant. The shell evaluates each redirection in terms of the (FileDescriptor, File) association at the time of evaluation. For example, in the statement:
... 1>File 2>&1

the file descriptor 1 is associated with the file specified by the File parameter. The shell associates file descriptor 2 with the file associated with file descriptor 1 (File). If the order of redirections were reversed, file descriptor 2 would be associated with the terminal (assuming file descriptor 1 had previously been) and file descriptor 1 would be associated with the file specified by the File parameter.

If a command is followed by an ampersand (&) and job control is not active, the default standard input for the command is the empty file /dev/null. Otherwise, the environment for the execution of a command contains the file descriptors of the invoking shell as modified by input and output specifications.

For more information about redirection, see Input and output redirection.

 

Unix command cat  is actually short for "catenate," i.e., link together. It accepts multiple filename arguments and copies them to the standard output. But let's pretend, for the moment, that cat and other utilities don't accept filename arguments and accept only standard input. Unix shell lets you redirect standard input so that it comes from a file. The notation command< filename does this; it sets things up so that command takes standard input from a file instead of from a terminal.

For example, if you have a file called fred that contains some text, then cat < fred will print fred's contents out onto your terminal. sort < fred will sort the lines in the fred file and print the result on your terminal (remember: we're pretending that utilities don't take filename arguments).

Similarly, command> filenamecauses the command's standard output to be redirected to the named file. The classic "canonical" example of this is date > now: the date command prints the current date and time on the standard output; the above command saves it in a file called now.

Input and output redirectors can be combined. For example: the cp command is normally used to copy files; if for some reason it didn't exist or was broken, you could use cat in this way:

$ cat  < file1>  file2

This would be similar to cp file1 file2.

It is also possible to redirect the output of a command into the standard input of another command instead of a file. The construct that does this is called the pipe, notated as |. A command line that includes two or more commands connected with pipes is called a pipeline.

Pipes are very often used with the less command, which works just like cat except that it prints its output screen by screen, pausing for the user to type SPACE (next screen), RETURN (next line), or other commands. If you're in a directory with a large number of files and you want to see details about them, ls -l | less will give you a detailed listing a screen at a time.

Pipelines can get very complex they can also be combined with other I/O directors. To see a sorted listing of the file freda screen at a time, type sort < fred | more. To print it instead of viewing it on your terminal, type sort < fred | lp.

Here's a more complicated example. The file /etc/passwd stores information about users' accounts on a UNIX system. Each line in the file contains a user's login name, user ID number, encrypted password, home directory, login shell, and other info. The first field of each line is the login name; fields are separated by colons (:).

To get a sorted listing of all users on the system, type:

$ cut -d: -f1 < /etc/passwd | sort

(Actually, you can omit the <, since cut accepts input filename arguments.) The cut command extracts the first field (-f1), where fields are separated by colons (-d:), from the input.

If you want to send the list directly to the printer (instead of your screen), you can extend the pipeline like this:

$ cut -d: -f1 < /etc/passwd | sort | lp

Now you should see how I/O directors and pipelines support the UNIX building block philosophy. The notation is extremely terse and powerful. Just as important, the pipe concept eliminates the need for messy temporary files to store output of commands before it is fed into other commands.

After sufficient practice, you will find yourself routinely typing in powerful command pipelines that do in one line what it would take several commands (and temporary files) in other operating systems to accomplish.

Old News ;-)

Tuesday Tiny Techie Tips

Tuesday Tiny Techie Tip -- 15 April 1997 Written by Jeff Youngstrom

Redirect stderr to a file
$ ls 2> file
This redirects just stderr output (associated with fd2) to the file. stdout is unchanged.
 

Redirect both stdout and stderr to a file
$ ls > file 2>&1
First the "> file" indicates that stdout should be sent to the file, then the "2>&1" indicates that stderr (fd2) should be sent to the same place as stdout (fd1).

To append to the file, only the stdout redirection must change since stderr is just hitching a lift on whatever stdout is doing.

$ ls >> file 2>&1

Redirect stdout to one file and stderr to another
 
$ ls > file 2> file2

Pipe one process' stdout and stderr to another's stdin
 
$ ls 2>&1 | wc
Here we combine stderr onto the stdout stream, then use "|" to pipe the result to the next process.
 

Combinations
 
$ sed 's/^#//' < file 2> sederr | \
	wc -l 2> wcerr | \
	awk '{print $NF}' > final 2> awkerr
Here I'm saving the error output from each command in the pipeline to a separate file ("sederr", "wcerr", "awkerr"), but letting stdout go straight through the pipe into the file "final". Input to sed(1) at the beginning of the pipe is redirected from the file "file"

Up to the TTTT index

Tuesday Tiny Techie Tips are all © Copyright 1996-1997 by Jeff Youngstrom.

Recommended Links

Linux I-O Redirection

Bourne Shell Scripting-Redirection - Wikibooks, collection of open-content textbooks

Input and output redirection in the Korn shell or POSIX shell

tee (Unix) - Wikipedia, the free encyclopedia


Copyright © 1996-2007 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. Submit comments This document is an industrial compilation designed and created exclusively for educational use and is placed under the copyright of the Open Content License(OPL). Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

Standard disclaimer: The statements, views and opinions presented on this web page are those of the author and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.

Last modified: March 15, 2008