Page 35 - Raspberry Pi as a Foundation for Boosting Computer and Technology Literacy
P. 35
Basics of shell commands 3.2
Figure 3.6
Example of redirecting
the command’s stdout to a file
shell allows us to redirect stdout and stderr using file descriptors. The
1> operator redirects stdout, while 2> redirects stderr. Consider the
following two slightly different commands:
ls -a ~ 1> file1 2> file2
ls -a /non-existent/directory/ 1> file1 2> file2
In the first case (Figure 3.6), the stdout of the ls command is redi-
rected to file1, which is created automatically. Concurrently, file2 is
also created but remains empty since the command has not returned
an error. It is worth noting that the terminal shows no output because
the stdout is sent to a file instead. The contents of file1 can be in-
spected using the cat command to confirm that it contains the stdout
from the ls command.
In the second case (Figure 3.7), the ls command attempts to access
a directory that does not exist on the system. As a result, the stderr is
captured and saved into file2, whereas file1 is empty. Similarly, the
stderr is not printed out in the terminal because it is redirected to a
file. This can be verified by using the cat command on file2.
Finally, to use the stdout of one command as the stdin of another
command, one has to utilize the pipe character ‘|’. This useful process
Figure 3.7 Example of redirecting the command’s stderr to a file
Figure 3.8
Example of using the stdout of one
command as the stdin of another
command
35