Bash 将 STDOUT 和 STDERR 的脚本记录和重定向到文件和屏幕,以便进行用户交互

Bash Scripting logging and redirection of STDOUT and STDERR to file and to screen so as to take have user interaction

我在成员 'reto' 的评论中看到了以下命令,这将满足我的大部分需求。不幸的是,我刚加入,无法回复。

他们做了我想做的大部分事情,但我也希望在我的脚本中的某些时间将 stdout 重定向到屏幕;如果 if 语句失败,当用户被要求输入用户名和密码时。然后,一旦用户交互完成,将标准输出恢复为日志记录。

任何帮助都会很棒。 更新

#this works for me

LOGFILE=./ClamAV_install_script.log

exec 3>&1 >$LOGFILE 2> >(tee -a $LOGFILE >&2)
# Everything below will go to the file 'ClamAV_install.log':
date

#all these go to screen
 {
 tail -40 ./ClamAV_install_script.log 


#To give option to scan full system
 printf "\n\n\nDo you wise to scan the full file system / ? \n" 
 read -p 'Type Y to scan: ' Conformation 
 printf "\nYou have entered: $Conformation\n" 
 } >&3
#!/bin/bash

set -e 

outfile=logfile

exec > >(cat >> $outfile)

exec 2> >(tee -a $outfile >&2)

#STDOUT 和 STDERR 将写入 $outfile,控制台上只会看到 STDERR

您可以通过在重定向之前将其复制到另一个文件描述符来保存流。

$: exec 3>&1 >>$outfile 2> >(tee -a $outfile >&2)
$: date     # goes to log
$: date >&3 # goes to console
Tue, Sep 15, 2020  8:24:19 AM

c.f。 https://www.gnu.org/software/bash/manual/html_node/Redirections.html