Add a logging function to your bash script

Submit to reddit

I write a lot of scripts that do various jobs and most of the time I’d like to have some log of what happened. So for most of them I add a function that helps logging.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/bin/bash
# log date format, customize it to your wishes
# see man date for help
DATE='date +%Y/%m/%d:%H:%M:%S'
# log file
LOG='/var/log/script.log'

function echo_log {
    echo `$DATE`" $1" >> $LOG
}
# start
echo_log "Script running"
# do something
echo_log "Doing this"
# done
echo_log "Script ended