Tuesday, March 10, 2009

A log script

The bash script below is an aid to maintain a record of daily events that could be used to study or measure progress. Copy the following code into a buffer and save the file as log.

#!/usr/bin/bash
log_file=log.txt
str_stamp=`date '+%Y-%m-%d %I:%M%p %a'`
str_date=`date +%Y-%m-%d`
#show log for the day
if test -a $log_file
then
grep "^$str_date" $log_file
else
touch $log_file
fi
read -p "$str_stamp: " log_comment
str_msg="$str_stamp: $log_comment"
echo $str_msg | cat >> $log_file

Make log an executable file:

$ chmod 755 log

To record an entry, execute log, and the log date and time prompts for your entry:

$ log
2003-10-24 10:26AM Fri:


Now type a test string, and press enter:

$ log
2003-10-24 10:26AM Fri: testing log script[enter]
$


Log saves your log entry to log.txt by default, and exits with your command prompt.
The next time you execute log, you are shown the events logged during the day:

2003-10-24 10:26AM Fri: testing log script
2003-10-24 10:29AM Fri:


Use less to view all entries, tail to view recent entries, or grep to search for entries in log.txt.