永久重定向
1.脚本中有大量数据需要重定向,那么逐条重定向所有的 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
$
2.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
$