Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding time stamp to log file in bash script

Tags:

bash

time

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?

like image 826
Joshua Avatar asked Oct 02 '13 10:10

Joshua


People also ask

How do I insert date and time in log file?

To enable date and timestamp in the log: Navigate to the Program Options dialog (Tools > Options...). In the Options tree, select Logging. The Logging options will appear. Select Display timestamps in the log.

What is $() in bash script?

$() Command Substitution According to the official GNU Bash Reference manual: “Command substitution allows the output of a command to replace the command itself.

How do I display date and time in bash?

Sample shell script to display the current date and time #!/bin/bash now="$(date)" printf "Current date and time %s\n" "$now" now="$(date +'%d/%m/%Y')" printf "Current date in dd/mm/yyyy format %s\n" "$now" echo "Starting backup at $now, please wait..." # command to backup scripts goes here # ...


1 Answers

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 
like image 107
fedorqui 'SO stop harming' Avatar answered Oct 08 '22 10:10

fedorqui 'SO stop harming'