Redirection (Unix)

From Free net encyclopedia

Image:Stdstreams-notitle.svg Redirection is a function common to most Unix shells which allow standard streams to be redirected to user-specified locations.

Programatically, it is done with the dup2(2) system call, or its less-flexible but higher-level stdio analogues, freopen(3) and popen(3).

Syntax in shells

Redirection is usually implemented by placing certain characters between commands. Typically, the syntax of these characters is as follows:

command1 > file1  

executes command1, placing the output in file1.

command1 < file1 

executes command1, using file1 as the source of input (as opposed to the keyboard).

command1 | command2   

Image:Pipeline-notitle.svg executes command1, using its output as the input for command2 (commonly called piping, since the "|" character is known as a "pipe").

A good example for command piping is combining echo with another command to achieve something interactive in a non-interactive shell, e.g. echo -e "user\npass" | ftp localhost. This would run the ftp client and enter user, press return, then pass.

In Unix shells derived from the original Bourne shell, the first two actions can be further modified by placing a number (the file descriptor) immediately before the character; this will affect which stream is used for the redirection. In shells derived from csh (the C shell), the syntax instead appends the & character to the redirect characters, thus achieving a similar result.

For example:

command1 2> file1

executes command1, directing the standard error stream to file1 (useful since standard error outputs to the terminal by default and is unaffected by redirection unless so specified).

The three tokens can be chained together to create complex commands, for example:

ls | grep '.sh' | sort > shlist    

lists the contents of the current directory, where this output is filtered to only contain lines which contain .sh, sort this resultant output alphabetically, and place the final output in shlist.

This type of construction is used very commonly in Unix shell scripts.it:Redirezione