Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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?

like image 988
eatloaf Avatar asked Dec 04 '25 19:12

eatloaf


1 Answers

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
like image 192
Mark Longair Avatar answered Dec 06 '25 09:12

Mark Longair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!