Ubuntu Unleashed 2019 Edition: Covering 18.04, 18.10, 19.04

(singke) #1

Redirecting Input and Output


You can create, overwrite, and append data to files at the command line, using
a process called input and output redirection. The shell recognizes several
special characters for this process, such as >, <, or >>.


In this example, the output of the ls command is redirected to create a file
named textfiles.listing:


Click here to view code image
matthew@seymour:~$ ls *.txt >textfiles.listing


Use output redirection with care because it is possible to overwrite existing
files. For example, specifying a different directory but using the same output
filename overwrites the existing textfiles.listing:


Click here to view code image
matthew@seymour:~$ ls /usr/share/doc/mutt-1.4/*.txt



textfiles.listing



Fortunately, most shells are smart enough to recognize when you might do
something foolish. Here, the bash shell warns that the command is attempting
to redirect output to a directory:


Click here to view code image
matthew@seymour:~$ mkdir foo
matthew@seymour:~$ ls >foo
bash: foo: Is a directory


Output can be appended to a file without overwriting existing content by
using the append operator, >>. In this example, the directory listing is
appended to the end of textfiles.listing instead of overwriting its
contents:


Click here to view code image
matthew@seymour:~$ ls /usr/share/doc/mutt-1.4/*.txt




textfiles.listing




You can use input redirection to feed data into a command by using the < like
this:


Click here to view code image
matthew@seymour:~$ cat < textfiles.listing


You can use the shell here operator, <<, to specify the end of input on the
shell command line:


Click here to view code image

Free download pdf