* Home :: Get a random password :: Get a multi-word password :: What is my IP? (v4 | v6)
* My projects

How to log the output of a bash script

Tags: howto

Date: 20240904


Many times we need to log the output of a script, especially when we run it programatically or from cronjobs and other sources.

Often it is not possible to use redirection from the command line (eg cmd > file.log), so let's see what else could be done from the script itself.

In my searches I found some serverfault web page where a very nice solution is proposed for this.

Basically you need to start your bash scripts with the following:

#!/bin/bash
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3 15
exec 1>/dev/shm/log.out 2>&1
# All the output will go to the file '/dev/shm/log.out' - change this to a more suitable path
        

The explanation given is:

    exec 3>&1 4>&2

    Saves file descriptors so they can be restored to whatever they were before redirection or used themselves to output to whatever they were before the following redirect.


    trap 'exec 2>&4 1>&3' 0 1 2 3 15

    Restore file descriptors for particular signals. Not generally necessary since they should be restored when the sub-shell exits.


    exec 1>log.out 2>&1

    Redirect stdout to file log.out then redirect stderr to stdout. Note that the order is important when you want them going to the same file. stdout must be redirected before stderr is redirected to stdout.

PS: I have also added fd 15 to the above to deal with SIGTERM signals.


(c)The Nux(tm) ;-)

No CSS, no Javascript, no some HTML.
No ads, no tracking, no cookies.