【问题标题】:Bash Scripting logging and redirection of STDOUT and STDERR to file and to screen so as to take have user interactionBash 脚本记录和 STDOUT 和 STDERR 重定向到文件和屏幕,以便进行用户交互
【发布时间】:2020-09-15 11:16:18
【问题描述】:

我在成员“reto”的评论中遇到了以下命令,这将满足我的大部分需求。不幸的是,我刚加入时无法发表评论。

他们做了我想做的大部分事情,但我也希望在我的脚本中的某些时间将标准输出重定向到屏幕;如果 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

【问题讨论】:

    标签: bash logging scripting stdout stderr


    【解决方案1】:

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

    $: 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
    

    参考https://www.gnu.org/software/bash/manual/html_node/Redirections.html

    【讨论】:

    • 这适用于命令分组,让一段代码进入屏幕 { date date } >&3
    • 你需要换行符或分号或其他一些命令终止元字符,不过 - { date; date; } >&3
    • 我把它们放在新的行上,下面对我有用。唯一的事情是一切都在一个新的线上。我无法在此处格式化代码以显示 { 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 '键入 Y 进行扫描:' 构象 printf "\n您已输入:$Conformation\n" } >&3
    猜你喜欢
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 2012-03-09
    • 2021-08-19
    • 2011-03-02
    • 1970-01-01
    • 2012-10-08
    相关资源
    最近更新 更多