- Shell Input and Output
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 exists, the shell erases (clobbers) the original file first. (Some shells have parameters that prevent clobbering. For example, enter set -C to avoid clobbering in bash.)
You can append the output to the file instead of overwriting it with the >> redirection syntax:
$ command >> file
This is a handy way to collect output in one place when executing sequences of related commands.
To send the standard output of a command to the standard input of another command, use the pipe character (|). 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.
- Standard Error
Occasionally, you may redirect standard output but find that the program still prints something to the terminal.
This is called standard error (stderr); it’s an additional output stream for diagnostics and debugging. For example, this command 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: cannot access /fffffffff: No such file or directory
You can redirect the standard error if you like. For example, to send standard output to f and standard error to e, use the 2> syntax, like this:
$ 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
- Standard Input Redirection
To channel a file to a program’s standard input, use the < operator:
$ head < /proc/cpuinfo
You will occasionally run into a program that requires this type of redirection, but because most Unix commands accept filenames as arguments, this isn’t very common. For example, the preceding command
could have been written as head /proc/cpuinfo.
Reference: How Linux Works: What Every Superuser Should Know by Brian Ward
Discover more from Embedded for All
Subscribe to get the latest posts sent to your email.