Читать книгу Linux Bible - Christopher Negus - Страница 127

Using file-redirection metacharacters

Оглавление

Commands receive data from standard input and send it to standard output. Using pipes (described earlier), you can direct standard output from one command to the standard input of another. With files, you can use less than (<) and greater than (>) signs to direct data to and from files. Here are the file-redirection characters:

< Directs the contents of a file to the command. In most cases, this is the default action expected by the command and the use of the character is optional; using less bigfile is the same as less < bigfile.
> Directs the standard output of a command to a file. If the file exists, the content of that file is overwritten.
2> Directs standard error (error messages) to the file.
&> Directs both standard output and standard error to the file.
>> Directs the output of a command to a file, adding the output to the end of the existing file.

The following are some examples of command lines where information is directed to and from files:

 $ mail root < ~/.bashrc $ man chmod | col -b > /tmp/chmod $ echo "I finished the project on $(date)" >> ~/projects

In the first example, the content of the .bashrc file in the home directory is sent in a mail message to the computer's root user. The second command line formats the chmod man page (using the man command), removes extra back spaces (col -b), and sends the output to the file /tmp/chmod (erasing the previous /tmp/chmod file, if it exists). The final command results in the following text being added to the user's project file:

 I finished the project on Sat Jun 15 13:46:49 EDT 2019

Another type of redirection, referred to as here text (also called here document), enables you to type text that can be used as standard input for a command. Here documents involve entering two less-than characters (<<) after a command, followed by a word. All typing following that word is taken as user input until the word is repeated on a line by itself. Here is an example:

 $ mail root cnegus rjones bdecker << thetext > I want to tell everyone that there will be a 10 a.m. > meeting in conference room B. Everyone should attend. > > -- James > thetext $

This example sends a mail message to root, cnegus, rjones, and bdecker usernames. The text entered between <<thetext and thetext becomes the content of the message. A common use of here text is to use it with a text editor to create or add to a file from within a script:

 /bin/ed /etc/resolv.conf <<resendit a nameserver 100.100.100.100 . w q resendit

With these lines added to a script run by the root user, the ed text editor adds the IP address of a DNS server to the /etc/resolv.conf file.

Linux Bible

Подняться наверх