Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging inside a bash script file

I have a pretty large script ( functions contains around 4000 lines of code) . Here is a part of it :

#!/bin/bash 


. ./functions > /dev/null 2>&1

some_function(){

while true
do

CHOICE=$(whiptail --menu "\n\n\n\n\n\n\n\n" --title "Tools" --nocancel $window 20 \
"1" "Option1" \
"2" "Option2" \
"3" "Option3" 3>&1 1>&2 2>&3)


case $CHOICE in

    1)echo $1 $2 $3;;
    2)echo $2 $1 $3;;                                       
    3)echo $3 $2 $1;;

esac
done
}



while true; do 
arr=()
for ((n=1; n<=$node_num; n++))
        do
        node+=($n NODE$n)
done


OPTION=$(whiptail --menu "\n\n\n\nPlease choose:\n\n\n" --title "tools" $window 20 "${node[@]}" \

case $OPTION in

        1) some_function 1 2 3 ;;  
        2) some_function 2 1 3 ;;
        3) some_function 3 1 2 ;;
esac
done

I want to log the commands executed in the script.

What I have tried so far is :

  1. #!/bin/bash -x --> this will log all the output , but will also "spam" the logs with unneeded information like variable values etc. However this seems to be the best way so far...
  2. I have tried #!/bin/bash -i , enabling history with set -o history . The disadvantage of this is it will log everything . When I call the function file for example it will log every single line as if it was executed .
  3. I have tried creating a log function :

    logthis(){
        ## print the command to the logfile
        echo "$(date) $@" >> $historyfile
        ## run the command and redirect it's error output
        ## to the logfile
        eval "$@" 2>> $historyfile
    }
    

    This seems to work most of the time. But when I do, for example:

    case $OPTION in
        1) logthis "some_function 1 2 3" ;;  
        2) some_function 2 1 3 ;;
        3) some_function 3 1 2 ;;
    esac
    

it will not work as I will lose the arguments 1 2 3

Do you have any other ideas of doing an elegant logging system inside a bash script?

like image 783
zlobul Avatar asked Mar 07 '23 22:03

zlobul


1 Answers

Get rid of the eval in your log function. Just write "$@" to execute the passed command.

logthis() {
    echo "$(date): $@" >> "$historyfile"
    "$@" 2>> "$historyfile"
}

Then you can log a command by simply prepending logthis. No need for extra quotes.

logthis some_function 1 2 3

This will very nicely preserve all the arguments--even if they have whitespace or other special characters.

I'd recommend a minor improvement to the echo command as well. If you use printf %q it'll log arguments with whitespace better.

echo "$(date):$(printf ' %q' "$@")" >> "$historyfile"
like image 72
John Kugelman Avatar answered Mar 14 '23 21:03

John Kugelman