Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I am trying to prepend log entries with a timestamp, but the generated timestamps do not seem to change over time:

#!/bin/sh

NOW=$(date +"%Y-%m-%d %H:%M:%S")

echo "$NOW Logging something"
sleep 2
echo "$NOW Logging something else"

Output for is:

2012-03-02 12:32:49 Logging something
2012-03-02 12:32:49 Logging something else

Does anybody know what I am doing wrong?

share|improve this question

3 Answers 3

up vote 2 down vote accepted

Compare and contrast with:

echo "`date +"%Y-%m-%d %H:%M:%S"` Logging something"
sleep 2
echo "`date +"%Y-%m-%d %H:%M:%S"` Logging something else"

In your version NOW is defined once as that time, and it stays as that for the rest of the run of the script. Above, the date is generated at the time of the "echo".

If you don't want to be adding date each time you can use a function:

#!/bin/sh

logtest() {
    echo "`date +"%Y-%m-%d %H:%M:%S"` $1"
}

logtest "Logging something"
sleep 2
logtest "Logging something else"
share|improve this answer
    
I understand that NOW is just defined once. But do I change that behaviour without using the date command in every echo command? –  Bertolt Mar 2 '12 at 12:07
    
The best way of doing this is to create a function that you can use. I'll edit the response above with an example. –  Niall Donegan Mar 2 '12 at 12:14
    
+1, bash function is the way to go –  glenn jackman Mar 2 '12 at 17:45

What's wrong with the good old logger command? :)

#!/bin/sh

logger -t yourprogram Hello, this is a message
sleep 2
logger -t yourprogram Hello, this is another message

Logger also allows you to use syslog priorities.

share|improve this answer
    
"logger" is brilliant if you have access to the syslogs in question! If you're a normal user you mightn't have such access. Surely you aren't running scripts as root while testing? "echo" to the console does have it's place! –  Niall Donegan Mar 2 '12 at 12:22

You create the timestamp only one time, when you declare the variable. It will not get updated automatically.

Try this:

echo `date +"%Y-%m-%d %H:%M:%S"` "Logging something"
share|improve this answer
    
This works. But I do not want to use the date command in every echo command, because it distracts from the actual output. –  Bertolt Mar 2 '12 at 11:58

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.