永久重定向

永久重定向

Content #

如果脚本中有大量数据需要重定向,那么逐条重定向所有的echo语句会很烦琐。这时可以用exec命令,它会告诉shell在脚本执行期间重定向某个特定文件描述符:

$ cat test10
#!/bin/bash
# redirecting all output to a file
exec 1>testout

echo "This is a test of redirecting all output"
echo "from a script to another file."
echo "without having to redirect every individual line"
$ ./test10
$ cat testout
This is a test of redirecting all output
from a script to another file.
without having to redirect every individual line
$

exec命令会启动一个新shell并将STDOUT文件描述符重定向到指定文件。脚本中送往STDOUT的所有输出都会被重定向。

也可以在脚本执行过程中重定向STDOUT:

$ cat test11
#!/bin/bash
# redirecting output to different locations

exec 2>testerror

echo "This is the start of the script"
echo "now redirecting all output to another location"

exec 1>testout

echo "This output should go to the testout file"
echo "but this should go to the testerror file" >&2
$
$ ./test11
This is the start of the script
now redirecting all output to another location
$ cat testout
This output should go to the testout file
$ cat testerror
but this should go to the testerror file
$

该脚本使用exec命令将送往STDERR的输出重定向到了文件testerror。接下来,脚本用echo语句向STDOUT显示了几行文本。随后再次使用exec命令将STDOUT重定向到testout文件。注意,尽管STDOUT被重定向了,仍然可以将echo语句的输出发送给STDERR,在本例中仍是重定向到testerror文件。

From #

Linux命令行与shell脚本编程大全