Chinaunix首页 | 论坛 | 博客
  • 博客访问: 90138
  • 博文数量: 48
  • 博客积分: 1980
  • 博客等级: 上尉
  • 技术积分: 500
  • 用 户 组: 普通用户
  • 注册时间: 2009-09-16 15:03
文章分类

全部博文(48)

文章存档

2009年(48)

我的朋友
最近访客

分类:

2009-09-17 21:23:38

重定向之exec
 
1.输入重定向(stdin)到文件
exec 要点
exec 6<&0          # 将文件描述符#6与stdin链接起来.# 保存stdin.
exec < data-file   # stdin被文件"data-file"所代替.
read a1            # 读取文件"data-file"的第一行.
read a2            # 读取文件"data-file"的第二行.
exec 0<&6 6<&-     # 现在将stdin从fd #6中恢复
                   #然后关闭fd #6 ( 6<&- ), 好让这个描述符继续被其他进程所使用.
                   # <&6 6<&-    这么做也可以.
 
2.输出重定向(stdout)到文件
同样的, exec >filename命令将会把stdout重定向到一个指定的文件中. 这样所有命令的输出就都会发送到那个指定的文件, 而不是stdout. exec N > filename会影响整个脚本或当前shell. 对于这个指定PID的脚本或shell来说, 从这句命令执行之后, 就会重定向到这个文件中, 然而
N > filename只会影响新fork出来的进程, 而不会影响整个脚本或shell. not the entire script or shell.
感谢你, Ahmed Darwish, 指出这个问题.
例子 16-2. 使用exec来重定向stdout
要点
LOGFILE=logfile.txt
exec 6>&1           # 将fd #6与stdout链接起来.# 保存stdout.
exec > $LOGFILE     # stdout就被文件"logfile.txt"所代替了.
在这块中所有命令的输出都会发送到文件$LOGFILE中.
{commands}
exec 1>&6 6>&-      # 恢复stdout, 然后关闭文件描述符#6.
 

I/O重定向是一种避免可怕的子shell中不可访问变量问题的方法.
阅读(455) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~