管道、重定向

带 noclobber 选项的输出重定向


[ian@echidna lpi103]$ set -o noclobber
[ian@echidna lpi103]$ ls x* z* >stdout.txt 2>stderr.txt
-bash: stdout.txt: cannot overwrite existing file
[ian@echidna lpi103]$ ls x* z* >|stdout.txt 2>|stderr.txt
[ian@echidna lpi103]$ cat stdout.txt
xaa
xab
[ian@echidna lpi103]$ cat stderr.txt
ls: z*: No such file or directory
[ian@echidna lpi103]$ set +o noclobber #restore original noclobber setting


使用 &> 或 &>> 将标准输出和标准错误重定向到同一个位置。

另一种方法是对文件描述符 n 进行重定向,然后使用 m>&n 或 m>>&n 将文件描述符 m 重定向到同一个位置。对输出进行重定向的次序很重要。


shell(包括 bash)还有 here-document 的概念,这是输入重定向的另一种形式。这使用 << 以及一个单词(比如 END),这个单词作为输入结束的标志。清单 71 演示了这种做法。


用 here-document 进行输入重定向


[ian@echidna lpi103]$ sort -k2 <<END
> 1 apple
> 2 pear
> 3 banana
> END
1 apple
3 banana
2 pear

find 命令有一个选项 -print0,它以 null 字符分隔输出的文件名而不是用新行字符。tarxargs 等命令有 -0(或 --null)选项,这使它们能够理解这种形式的参数。

 更多的 xargs 示例



[ian@echidna lpi103]$ # pass all arguments at once
[ian@echidna lpi103]$ find . -name "text*2" |xargs echo
./text2 ./backup/text1.bkp.2 ./text sample2
[ian@echidna lpi103]$ # show the files we created earlier with the touch command
[ian@echidna lpi103]$ ls f[0-n]*|xargs echo
f1 f1a f2 f3 f4 f5 f6 f7 f8 f9
[ian@echidna lpi103]$ # remove them in one stroke
[ian@echidna lpi103]$ ls f[0-n]*|xargs rm
[ian@echidna lpi103]$ # Use a replace string
[ian@echidna lpi103]$ find . -name "text*2" |xargs -i echo - '{}' -
- ./text2 -
- ./backup/text1.bkp.2 -
- ./text sample2 -
[ian@echidna lpi103]$ # Limit of one input line per invocation
[ian@echidna lpi103]$ find . -name "text*2" |xargs -l1 echo
./text2
./backup/text1.bkp.2
./text sample2
[ian@echidna lpi103]$ # Limit of one argument per invocation
[ian@echidna lpi103]$ find . -name "text*2" |xargs -n1 echo
./text2
./backup/text1.bkp.2
./text
sample2


 

 

posted @ 2008-08-18 18:32  xiaoyixy  阅读(306)  评论(0编辑  收藏  举报