天天看點

Streams, pipes, and redirects

http://www.ibm.com/developerworks/linux/library/l-lpic1-103-4/index.html

I、輸出重定向
1. The n in n> or n>> refers to the file descriptor. If it omitted, then standard output is assumed.
n>和n>>中的n表示檔案描述符,預設為标準輸出1

2. Output redirection using n> usually overwrites existing files. You can control this with
the noclobber option of the set builtin. If it has been set, you can override it using n>|
使用set指令的noclobber選項可以防止輸出重定向意外覆寫已存在的檔案,此時可以使用n>|強制覆寫

3. redirect both standard output and standard error to the same place
同時重定向标準輸出和标準錯誤輸出到同一個地方:
    3.1 &> or &>>  
    3.2 redirect file descriptor n and then redirect file descriptor m to the same place using the construct m>&n or m>>&n. 
    重定向的先後順序很重要,2>&1 >output.txt的效果和 >output.txt 2>&1是不同的:
    2>&1 >output.txt表示先把标準錯誤重定向到目前stdout輸出的地方,然後把标準輸出重定向到output.txt
    >output.txt 2>&1表示把标準錯誤重定向到stdout輸出的地方,而此時stdout輸出的地方就是output.txt,和期望的結果相符。

4. ignore either standard output or standard error entirely /dev/null
/dev/null可以消費任何輸入


II、輸入重定向
1.  < operator
2. Shells, including bash, also have the concept of a here-document, which is another form of input redirection. 
This uses the << along with a word, such as END, for a marker or sentinel to indicate the end of the input. 
If you use <<- instead of just <<, then leading tabs are stripped.


III、管道
1. One thing to note is that pipelines only pipe stdout to stdin
2. One advantage of pipes on Linux and UNIX systems is there is no intermediate file involved with a pipe.
管道的優點是不需要使用檔案的存儲轉發,而是直接進行通信


IV、将輸出作為指令參數
1. use the output of a command or the contents of a file as arguments to a command rather than as input.
将一個指令的輸出或者一個檔案的内容作為另一個指令的參數而不是輸入

常用的指令有xargs, find -exec, 

Xargs:
The xargs command reads standard input and then builds and executes commands with the input as parameters.
If no command is given, then the echo command is used.
By default, xargs breaks the input at blanks,and each resulting token becomes a parameter. However, when xargs builds the command, 
it will pass as many parameters at once as it possibly can. You may override this behavior with the -n , or --max-args , parameter.
If the input contains blanks that are protected by single or double quotes, or by backslash escaping, then xargs will not break 
the input at such points. use the -I option to specify a replacement string. When you do this, only one argument will be passed to 
each command. You can also use the -L option of xargs to have it treat lines as arguments rather than the default of individual 
blank-delimited tokens. Using the -I option implies -L 1 .use the --show-limits option to display the default limits of xargs , 
the -s option to limit the size of output commands to a specific maximum number of characters