我一直在编写一些bash脚本,主要用于自动(crontab)操作。常见的过程是通过重复命令将任何输出记录到日志文件中(可以存储和通过电子邮件发送):
logfile=/tmp/logs/$(basename "$0" .sh)-$(date +%Y%m%d).log
action1 >> "$logfile" 2>&1
hidden_action
action2 >> "$logfile" 2>&1
echo "message" >> $logfile
action3 >> "$logfile" 2>&1
我可以只使用exec
,这样默认行为就像预期的那样,不会重定向预期输出的每一行:
logfile=/tmp/logs/$(basename "$0" .sh)-$(date +%Y%m%d).log
exec > "$logfile" 2>&1
action1
hidden_action > /std/null
action2
echo "message"
action3
(可以吗?)
但是,有时我需要手动运行脚本,有些脚本需要几分钟(甚至几小时)。所以我会在后台运行它们,cat
或tail
不断地运行日志文件。
我知道我可以使用
这样的行tee
输出
exec > >(tee -a "$logfile") 2>&1
但是,我想要以下行为:
stdout
和stderr
默认会写在$logfile
上。stderr
也会被发送到屏幕。类似的东西:
logfile=/tmp/logs/$(basename "$0" .sh)-$(date +%Y%m%d).log
exec ... # SOMETHING
action1 # any output logged, errors also to screen
echo "checkpoint" > $screen # print only to screen, not logged
hidden_action > $null # any output goes neither to log nor to screen
action2 # any output logged, errors also to screen
echo "message" # just logged
action3 # any output logged, errors also to screen
如果无法将其作为默认行为,那么对于每一行:
action1 >#any output logged, errors also to screen
echo "checkpoint"
hidden_action > /dev/null
action2 >#any output logged, errors also to screen
echo "message" >> "$logfile"
action3 >#any output logged, errors also to screen
提前感谢您的任何线索。