简体   繁体   中英

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?

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

可能的原因是终端和sh中日期的路径不同:尝试使用直接从命令行使用的日期的完整路径,即$(/bin/date)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM