32

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?

4
  • 1
    Cannot tell you why, but date +"Time: %C" >>Debug.log would seem to do what you want, probably more transparently and succinctly. Commented Oct 2, 2013 at 10:50
  • Also, grep thing | grep -v grep can usually be refactored to something like grep [t]hing where the idea is to use a regex which does not match itself. Commented Oct 2, 2013 at 10:51
  • 2
    Note you are outputting to Debug.log, while you should indicate the full path of that file. Commented Oct 2, 2013 at 10:58
  • @fedorqui this is what it ended up being. Thanks for the tip. Commented Oct 2, 2013 at 13:07

3 Answers 3

50

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
Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.