Search code examples
bashloggingscriptingstdoutstderr

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


I came across the below commands in a comment by member 'reto' which will do most what I want. unfortunately I can't comment back as I just joined.

They do most of what I want to do but I would also like to have stdout being redirected screen at certain times in my script; when the user is being asked for a username and password if an if statement fails. Then once the user interaction is complete to revert stdout to logging.

Any help would be great. update

#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 and STDERR will be written to $outfile, only STDERR will be seen on the console


Solution

  • You can save a stream by dup'ing it onto another file descriptor before redirecting it.

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