3.9 KiB
Redirect input, output and standard error
Everything in GNU systems is a file. The keyboard and the terminal are also a file. The keyboard is used for input and the terminal is used by commands as output.
The files can be found in directory "fd", which stands for file descriptor)
cd /dev/fd/ ls -l
total | 0 | |||||||||
lr-x—— | 1 | user | user | 64 | dec | 15 | 10:31 | 0 | -> | /tmp/babel-yl1RTd/ob-input-izpXuk |
l-wx—— | 1 | user | user | 64 | dec | 15 | 10:31 | 1 | -> | pipe:[42063] |
lr-x—— | 1 | user | user | 64 | dec | 15 | 10:31 | 17 | -> | /dev/pts/0 |
l-wx—— | 1 | user | user | 64 | dec | 15 | 10:31 | 2 | -> | /tmp/emacsA1M18o |
- standard input stream is bound to /dev/fd/0
- standard output (stout) stream is bound to /dev/fd/1
- standard errror (stderr) stream is bound to /dev/fd/2
During interaction a terminal gets written to stdin (dev/fd/0), which a command read. The command then do an action and writes the output (stout or stderr) where it will read by the terminal and is displayed to the user.
To redirect use the operator `>` as follows:
- `command > file_to_redirect`
The operator `>` redirects stout, i.e., is the same that 1>. This code creates a new file with the list of files present in the actual directory:
ls -l > file_redirect.txt cat file_redirect.txt
total | 32 | |||||||
-rw-r–r– | 1 | user | user | 15782 | dec | 15 | 10:49 | bash_tutorial.org |
-rw-r–r– | 1 | user | user | 0 | dec | 15 | 10:49 | file_redirect.txt |
-rw-r–r– | 1 | user | user | 11895 | dec | 9 | 17:44 | markdown.md |
-rw-r–r– | 1 | user | user | 121 | dec | 9 | 17:17 | README.org |
Use "2>&1" to redirect stderr with the stout. Using an arbitrary word and redirect it to the file should print a warning message that is redirected to the file:
ls -l > file_redirect.txt paco >> file_redirect.txt 2>&1 cat file_redirect.txt
total | 32 | |||||||
-rw-r–r– | 1 | user | user | 15995 | dec | 15 | 12:39 | bash_tutorial.org |
-rw-r–r– | 1 | user | user | 0 | dec | 15 | 13:41 | file_redirect.txt |
-rw-r–r– | 1 | user | user | 11895 | dec | 9 | 17:44 | markdown.md |
-rw-r–r– | 1 | user | user | 121 | dec | 9 | 17:17 | README.org |
bash: | line | 2: | paco: | command | not | found |
Use the "<" operator to pass commands to the file:
ls -l > file_redirect.txt paco >> file_redirect.txt 2>&1 sort < file_redirect.txt cat file_redirect.txt
bash: | line | 2: | paco: | command | not | found | ||
-rw-r–r– | 1 | user | user | 0 | dec | 15 | 13:44 | file_redirect.txt |
-rw-r–r– | 1 | user | user | 121 | dec | 9 | 17:17 | README.org |
-rw-r–r– | 1 | user | user | 16501 | dec | 15 | 13:41 | bash_tutorial.org |
total | 24 | |||||||
total | 24 | |||||||
-rw-r–r– | 1 | user | user | 16501 | dec | 15 | 13:41 | bash_tutorial.org |
-rw-r–r– | 1 | user | user | 0 | dec | 15 | 13:44 | file_redirect.txt |
-rw-r–r– | 1 | user | user | 121 | dec | 9 | 17:17 | README.org |
bash: | line | 2: | paco: | command | not | found |