我有一个大的bash脚本,我想全局将所有stdout/stderr重定向到一个文件,除了一些进度指示器,如特定的回显消息.例如,请考虑以下脚本
#!/bin/bash
# all stdout and stderr go to out.log
exec &> out.log
special_echo "starting"
# many other commands go here
# which output both the stdout and stderr
# also some special_echo commands in here,
# for example
echo "msg1"
special_echo "middle"
echo "msg2" >&2
special_echo "finished"
Run Code Online (Sandbox Code Playgroud)
当它运行时,输出应该是
$ ./script
starting
middle
finished
$
Run Code Online (Sandbox Code Playgroud)
但是,out.log应该包含
msg1
msg2
Run Code Online (Sandbox Code Playgroud)
如何实现special_echo功能?我已经尝试使用文件描述符并回显,但无法让它显示在屏幕上.
有没有办法实现这一点,而无需将重定向添加到每一行或做这样的答案?
是的,使用另一个文件描述符是要走的路:
#!/bin/bash
exec 3>&1
special_echo () {
echo "$@" >&3
}
exec &> out.log
special_echo "starting"
echo "msg1"
special_echo "middle"
echo "msg2" >&2
special_echo "finished"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2946 次 |
| 最近记录: |