[nycbug-talk] Scripting(Date&Time) Question
Steven Kreuzer
skreuzer at f2o.org
Fri Dec 29 14:02:30 EST 2006
On Dec 29, 2006, at 1:41 PM, michael wrote:
> On Fri, 29 Dec 2006 13:32:56 -0500
> Kevin Reiter <tux at penguinnetwerx.net> wrote:
>
>> All,
>>
>> Fairly simple (I think) question here:
>>
>> When echoing the date into a logfile from a script, I'm noticing the
>> time never changes.
>>
>> Here's an example of the resulting log entries:
>>
>> 12/29/2006 13:15:47: www_data compressed.
>> 12/29/2006 13:15:47: Database dump done.
>> 12/29/2006 13:15:47: Checksums created.
>> 12/29/2006 13:15:47: Other stuff done.
>> 12/29/2006 13:15:47: Sending files to remote server...
>> 12/29/2006 13:15:47: Files sent.
>>
>> Here's the code snippet that defines the date format:
>>
>> DATE=`date +'%m/%d/%Y %H:%M:%S'`
>>
>> Here's the actual code snippets in the script that echo the $DATE
>> into the log:
>>
>> echo "$DATE: www_data compressed." >> www_backup.log
>> echo "$DATE: Database dump done." >> www_backup.log
>> echo "$DATE: Checksums created." >> www_backup.log
>> ...etc...
>>
>> Is there a reason the time isn't updated when the script runs? I'm
>> guessing here that the $DATE variable grabs the current time when the
>> script kicks off and doesn't update it in real-time as the script
>> proceeds - would that be a close guess?
>>
>> What would need to be changed in order for the current time to be
>> entered into the logfile? Any assistance would be most appreciated.
>>
>> Kev
>
> At first blush, it looks like you only initialize $DATE once at the
> start. So.. your assumption looks right from here.
>
> --
>
> michael
The easiest way to work around it would be to write a function called
log which looks something like the example script below:
#### Start Script
function log() {
NOW=$(date +'%m/%d/%Y %H:%M:%S')
echo "${NOW} - ${1}"
}
log "OMG"
sleep 10
log "WTF"
sleep 10
log "BBQ"
#### End Script
This was written in ksh, but it should work in bash or whatever
inferior shell you use ;)
Basically, you have a function called log that you pass a string, and
then when the function gets called the variable $NOW gets set with
the current date. (The variable $1 holds the string that you passed it.)
example output:
$ ./example.sh
12/29/2006 13:51:19 - OMG
12/29/2006 13:51:29 - WTF
12/29/2006 13:51:39 - BBQ
More information about the talk
mailing list