Content #
可以用exec命令分配用于输出的文件描述符。和标准的文件描述符一样,一旦将替代性文件描述符指向文件,此重定向就会一直有效,直至重新分配。
$ cat test13
#!/bin/bash
# using an alternative file descriptor
exec 3>test13out
echo "This should display on the monitor"
echo "and this should be stored in the file" >&3
echo "Then this should be back on the monitor"
$ ./test13
This should display on the monitor
Then this should be back on the monitor
$ cat test13out
and this should be stored in the file
$
这个脚本使用exec命令将文件描述符3重定向到了另一个文件。当脚本执行echo 语句时,文本会像预想中那样显示在STDOUT中。但是,重定向到文件描述符3的那行echo语句的输出进入了另一个文件。这样就可以维持显示器的正常输出,并将特定信息重定向到指定文件(比如日志文件)。
也可以不创建新文件,而是使用exec命令将数据追加到现有文件:
exec 3>>test13out
现在,输出会被追加到test13out文件,而不是创建一个新文件。
From #
Linux命令行与shell脚本编程大全