1

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?

3 Answers 3

3

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"
3
  • 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, 2012 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. Mar 2, 2012 at 12:14
  • +1, bash function is the way to go Mar 2, 2012 at 17:45
3

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.

1
  • "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! Mar 2, 2012 at 12:22
0

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"
1
  • 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, 2012 at 11:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .