Joshua
Joshua

Reputation: 1584

Adding time stamp to log file in bash script

My script is as follows

if ps ax | grep -v grep | grep ./program > /dev/null
    then
        exit
    else
        echo "---------------------------------------------------" >> Debug.log
        echo "Starting program at:  $(date)" >> Debug.log
        ./program >> Debug.log 2>&1
fi
exit

Via crontab, this script is run every minute. It checks to see if a certain program is running, if it is, great, if not, starts it up.

Now I would like to append timestamps every time the script runs into Debug.log if it found ./program to be running. So under the then line, I added:

echo "Time: $(date)" >> Debug.log

This command does not output anything to Debug.log. It does work however directly from the command line. Why is that so, and can I remedy the problem?

Upvotes: 32

Views: 80645

Answers (3)

ntg
ntg

Reputation: 14075

As mentioned by @{fedorqui 'SO stop harming'} using >> appends to the end of the log file.

Alternatively, this will also limit the log to 1MB:

tail -c 1MB fail.log; echo $(date) run script > file.log

Upvotes: 0

fedorqui
fedorqui

Reputation: 289565

Note you are outputting to Debug.log, while you should indicate the full path of that file: echo "Time: $(date)" >> /path/to/Debug.log.


In general, whenever you want to add timestamp to a log file, you can use:

echo "Time: $(date). Some error info." >> /path/to/your/file.log

date will expand to something like Fri Sep 9 12:18:02 CEST 2016. In that case, you may prefer to use some date flags to have a more parseable date:

$ date "+%FT%T"
2016-09-09T12:18:23

Or, even better, using the ISO 8601 format:

$ date -Iseconds
2016-09-09T12:18:23+0200

All together:

echo "Time: $(date -Iseconds). Some error info." >> /path/to/your/file.log

Upvotes: 50

Wintermute
Wintermute

Reputation: 1531

Possible reason is different paths for date in terminal and sh: try using full path to the date which you use directly from command line, i.e. $(/bin/date)

Upvotes: 3

Related Questions