Chinaunix首页 | 论坛 | 博客
  • 博客访问: 968969
  • 博文数量: 200
  • 博客积分: 5011
  • 博客等级: 大校
  • 技术积分: 2479
  • 用 户 组: 普通用户
  • 注册时间: 2008-06-27 15:07
文章分类

全部博文(200)

文章存档

2009年(12)

2008年(190)

我的朋友

分类:

2008-07-17 14:56:13

这个帖子可以帮助我们很好的理解重定位问题。
转载自CU shell版:


此贴是从另外一个主题移过来的,代码如下
代码:

CODE:
exec 9>&1
comd1 2>&1 >&9 9>&- | comd2 9>&-
exec 9>&-

comd1和comd2代表任意的命令。
该脚本使comd1的错误输出通过管道作为comd2的输入,comd1的正常输出仍然保持。

QUOTE:
原帖由 "r2007" 发表:

正相反,是从左向右操作的。
fd: 文件描述符,默认有0,1,2分别用作输入、输出和错误输出。可以理解为C中的file handle,也可以理解为文件指针,shell默认有10个fd。
先写到这儿,下班了。

接着说:
exec 9>&1 #把fd1的指针复制到fd9,即dup(1,9),或者干脆理解为fd9=fd1
#注意,此时fd9和fd1同时指向一个文件。也可认为将fd1的指针保存在fd9中一份
comd1 2>&1 >&9 9>&- | comd2 9>&-
#这一句比较麻烦
#首先shell创建一个pipe,然后分别folk两个subshell
#看看第一个subshell做了什么?
#首先每个subshell都精确拷贝一份父进程的fd表,即0,1,2和9都复制过来了
#然后将fd1指向pipe文件,此时fd9仍然保存着父进程中fd1的文件指针,如果父进程没有重定向的话,就是stdout
#然后处理这段2>&1 >&9 9>&重定向命令。既
#fd2=fd1; fd1=fd9; fd9=null
#结果是fd2指向fd1原先指向的pipe文件,fd1指向fd9指向的文件,即stdout,然后将fd9关闭,由于这时fd1和fd9同时指向同一个文件stdout,所以stdout并没有真正关闭,只是减少打开次数。
#最后subshell执行comd1命令,comd1要输出时取fd1中的指针,即stdout,输出错误时,取fd2中的指针,即pipe,这样comd2从pipe中只得到了comd1输出的错误信息。
#再看看第二个subshell做了什么?
#同样精确拷贝一份父进程的fd表
#然后将fd0指向pipe文件。
#然后处理这段 9>&重定向命令。既关闭fd9。

exec 9>&- #回到父进程,关闭fd9


发表于 2005-1-17 08:19 
shell的输入与输出

for example
一开始
fd1=pipe
fd2=stderr
fd9=stdout

cmd1 2>&1 >&9 9>&− | cmd2 ... 等价于
fd2=fd1 (fd2=pipe)
fd1=fd9 (fd1=stdout)
fd9=null

下面是一个很全面的定义:
Redirector Function

cmd1 | cmd2
Pipe; take standard output of cmd1 as standard input to cmd2

> file
Direct standard output to file

< file
Take standard input from file

>> file
Direct standard output to file; append to file if it already exists

>| file
Force standard output to file even if noclobber is set

n>| file
Force output to file from file descriptor n even if noclobber is set

<> file
Use file as both standard input and standard output

n<> file
Use file as both input and output for file descriptor n

<< label
Here-document; see text

n> file
Direct file descriptor n to file

n< file
Take file descriptor n from file

n>> file
Direct file descriptor n to file; append to file if it already exists

n>&
Duplicate standard output to file descriptor n

n<&
Duplicate standard input from file descriptor n

n>&m
File descriptor n is made to be a copy of the output file descriptor

n<&m
File descriptor n is made to be a copy of the input file descriptor

&>file
Directs standard output and standard error to file

<&-
Close the standard input

>&-
Close the standard output

n>&-
Close the output from file descriptor n

n<&-
Close the input from file descriptor n

阅读(1789) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~