Linux - Redirection of Standard output/input

来源:互联网 发布:2016年全国经济数据 编辑:程序博客网 时间:2024/06/05 07:31

转自 http://doc.dev.md/lsst/ch02sec15.html


There are three main redirection symbols >,>>,<
>     if file already exist, it will be overwritten else new file is created.
        After input, press CTRL + D to save file.
>>    if file exist , it will be opened and new information/data will be written to END of file, without losing previous information/data, And if file is not exist, then new file is created.
<    To take input to Linux-command from file instead of key-board.

In Linux (And in C programming Language) your keyboard, screen etc are all treated as files. Following are name of such files
Standard FileFile Descriptors numberUseExamplestdin0as Standard input Keyboardstdout1as Standard outputScreenstderr2as Standard error Screen
By default in Linux every program has three files associated with it, (when we start our program these three files are automatically opened by your shell). The use of first two files (i.e. stdin and stdout) , are already seen by us. The last file stderr (numbered as 2) is used by our program to print error on screen. You can redirect the output from a file descriptor directly to file with following syntax
Syntax: 
file-descriptor-number>filename

Note:
command or script  >file_name等同于command or script  1>file_name,即将stdout的内容redirect到file_name中。如果要将stderr的内容redirect到file中,则需要明确写出为:
command or script  2>file_name

如果直接使用File Descriptors number来redirect,则语法为:from>&destination
如: 1>&2

在script中,echo语句都将输出到stdout中,如果要将其转为stderr输出,则需要在echo语句后面加1>&2,如 echo "Error : Number are not supplied" 1>&2
如此一来,可以将script的输出信息同时分别redirect到不同的文件中,如 script  >info_file  2>error_file
(等同于 script  1>info_file  2>error_file)

>和<可以同时使用,如 command  <input_file   >output_file
并且没有顺序限制,也可以这种使用 command  >output_file  <input_file



0 0
原创粉丝点击