开发者

In Bash, how can I lazy eval 'date'?

开发者 https://www.devze.com 2023-04-13 08:35 出处:网络
I have a script that outputs with timestamps but I can\'t manage to have the date evaluate when the specific line is reached; all of the stamps have the time of the script\'s first call, that is, they

I have a script that outputs with timestamps but I can't manage to have the date evaluate when the specific line is reached; all of the stamps have the time of the script's first call, that is, they're all the same, even though the script takes hours to complete.

I'm trying 开发者_高级运维this:

TIMESTAMP=`date +"%H:%M:%S --"`
...

eval "echo $TIMESTAMP Starting backup"
...
eval "echo $TIMESTAMP Doing something here"

What am I doing wrong?


The problem is that the backticks evaluate the command inside when you assign to DATE_COMMAND. You could do the following instead:

DATE_COMMAND='date +"%H:%M:%S --"'
...
...
eval $DATE_COMMAND
...
...
eval $DATE_COMMAND

To be honest, though, I would avoid eval and just make this a function:

timestamp() {
    date +"%H:%M:%S --"
}
...
...
timestamp
...
...
timestamp


Aliases are handy, easy expansion in an echo line. E.g.:

#!/bin/bash

alias now='date +%T'
echo $(now)
sleep 10
echo `now`
sleep 1
echo $(now) My Log line

Yielding:

15:13:56
15:14:06
15:14:07 My Log line


You need to reassign the TIMESTAMP variable before each eval executes to the current date / time, otherwise the original timestamp value will just be redisplayed. For example:

TIMESTAMP=`date +"%H:%M:%S --"`
eval "echo $TIMESTAMP"
...
TIMESTAMP=`date +"%H:%M:%S --"`
eval "echo $TIMESTAMP"


Why don't you write a function to do this?

$ function printdate {
>     echo `date +"%H:%M:%S --"`
> }
0

精彩评论

暂无评论...
验证码 换一张
取 消