永久重定向

该博客介绍了如何使用`exec`命令在Shell脚本中重定向输出,避免为每个单独的`echo`语句指定重定向。通过`exec 1>`将STDOUT重定向到文件,`exec 2>`则可以改变错误输出的流向。示例脚本展示了如何在执行过程中改变STDOUT和STDERR的重定向目标,使得输出分别进入不同的文件。
摘要由CSDN通过智能技术生成

如果脚本中有大量数据需要重定向,那重定向每个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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值