4.11. Using Shell Redirection and Piping

The Unix/Linux philosophy revolves around the concept of programs as building blockseach one intended to do one job and do it well. Redirection lets you connect these commands to files, and piping enables you to plug commands together like a child's toy.

4.11.1. How Do I Do That?

Each command has three numbered file descriptors that are opened automatically:

standard input (stdin, file descriptor 0)

The normal input to the program

standard output (stdout, file descriptor 1)

The normal output from the program

standard error (stderr, file descriptor 2)

Error messages from the program

By default, these file descriptors are connected to the terminal, if one is available, so standard input comes from the terminal keyboard, and standard output and standard error go to the terminal screen. Programs may open any other connections they need to read or write files, communicate with other local programs, or communicate with programs over the network.

4.11.1.1. Redirection

To redirect the output of a program to a file, use the greater-than ( > ) symbol followed by the name of the file:

$ cal 7 2006

July 2006

Su Mo Tu We Th Fr Sa

                   1

 2  3  4  5  6  7  8

 9 10 11 12 13 14 15

16 17 18 19 20 21 22

23 24 25 26 27 28 29

30 31

$ cal 7 2006 > month.txt

$ cat month.txt

July 2006

Su Mo Tu We Th Fr Sa

                   1

 2  3  4  5  6  7  8

 9 10 11 12 13 14 15

16 17 18 19 20 21 22

23 24 25 26 27 28 29

30 31

When you redirect output with > , the previous contents of the file are overwritten. To append (add) to the file, use >> :

$ cal 3 2009 >> month.txt

$ cat month.txt

July 2006

Su Mo Tu We Th Fr Sa

                   1

 2  3  4  5  6  7  8

 9 10 11 12 13 14 15

16 17 18 19 20 21 22

23 24 25 26 27 28 29

30 31

July 2006

Su Mo Tu We Th Fr Sa

                   1

 2  3  4  5  6  7  8

 9 10 11 12 13 14 15

16 17 18 19 20 21 22

23 24 25 26 27 28 29

30 31

March 2009

Su Mo Tu We Th Fr Sa

 1  2  3  4  5  6  7

 8  9 10 11 12 13 14

15 16 17 18 19 20 21

22 23 24 25 26 27 28

29 30 31

Error messages are not sent to standard output, so you can still see the messages even when standard output is redirected:

$ cal 17 2009 > month.txt

cal: illegal month value: use 1-12

To redirect error messages, place the file descriptor number ( 2 ) in front of the redirection symbol ( > or >> ):

$ cal 17 2009 2 >errors

Вы читаете Fedora Linux
Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату