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: $ 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 will overwrite the existing textfiles.listing:
$ 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:
Output can be appended to a file without overwriting existing content by using the append operator, >>. In this example, the directory listing will be appended to the end of textfiles.listing instead of overwriting its contents:
$ 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:
$ cat < textfiles.listing
You can use the shell here operator, <<, to specify the end of input on the shell command line:
> echo ""this is a simple script""
$ cat simple_script echo ""this is a simple script""
In this example, the shell will feed the cat command you are typing (input) until the pattern done is recognized. The output file simple_script is then saved and its contents verified. This same technique can be used in scripts to create content based on the output of various commands and define an end-of-input or delimiter.
Was this article helpful?