1.14 Shell Input and Output


1.14 Shell Input and Output

Now that you are familiar with basic Unix commands, files, and directories, you are ready learn the shell's I/O tricks. You can redirect the standard input and output. Let's start with standard output.

If you wish to send the output of command to a file instead of the terminal, use the > redirection character:

  command  >  file  

The shell creates file if it does not already exist. If file does exist, the shell erases the original file first; this is called clobbering the file. Some shells have parameters that prevent clobbering. For example, you can type set -C to avoid clobbering in bash .

If you don't want to overwrite a file, you can append the output to the file instead with the >> redirection syntax:

  command  >>  file  

This is a handy way to collect output in one place when repeatedly executing a variant of the same command.

To send the output of a command to the input of another command, use the pipe ( ). To see how this works, try these two commands:

 head /proc/cpuinfo head /proc/cpuinfo  tr a-z A-Z 

You can send output through as many piped commands as you wish; just add another pipe ( ) before each additional command.

1.14.1 Standard Error

Occasionally, you may redirect standard output but find that the program still prints something on the terminal. This is standard error ( stderr ), an additional output stream for diagnostics and debugging. Try this command, which produces an error:

 ls /fffffffff > f 

After completion, f should be empty, but you still see the following error message on the terminal as standard error:

 ls: /fffffffff: No such file or directory 

You can redirect the standard error if you like. If you want to send standard output to f and standard error to e , use the following command:

 ls /fffffffff > f 2> e 

The number 2 specifies the stream ID that the shell modifies. Stream ID 1 is standard output (the default), and 2 is standard error.

You can also send the standard error to the same place as stdout with the >& notation. For example, to send both standard output and standard error to the file named f , try this command:

 ls /fffffffff > f 2>&1 

1.14.2 Standard Input Redirection

It is also possible to channel a file to a program's standard input with the < operator. Here's an example:

 head < /proc/cpuinfo 

You will occasionally run into a program that requires this sort of redirection. However, because most Unix commands accept filenames as arguments, this redirection isn't very common. For example, the preceding command could have been written as head /proc/cpuinfo .




How Linux Works
How Linux Works: What Every Superuser Should Know
ISBN: 1593270356
EAN: 2147483647
Year: 2004
Pages: 189
Authors: Brian Ward

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net