Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing current date and time in DOS script

Tags:

date

time

dos

I have a script that prints the date and time followed by a string in a log.

echo %DATE%_%TIME% Processing %%f >> process.log

The problem is that the date and time is always the date and time when the script is started. I've been running the script overnight, and still has the same date and time. Is there a way to update them so it shows the current date and time when the string is printed to the log file?

like image 321
Rayne Avatar asked Sep 21 '12 05:09

Rayne


People also ask

How to print current date in cmd?

Bookmark this question. Show activity on this post. In Linux I do date +"%Y%m%d%H%M%S" to print a date and time label.

How to get current date in dos?

On a Microsoft Windows system, you can obtain the current date using the date /t command (the /t option prevents the command from prompting for a change to the the date) or by using echo %date% to display the contents of the date environment variable.


1 Answers

The fact that you have %%f indicates your echo command is in a FOR loop. The entire FOR loop is parsed at once, and %DATE% is expanded at parse time. The command is not re-parsed for each iteration, so that is why you get the same value for each iteration. You get the value that existed before the FOR statement is executed!

The solution is delayed expansion. Put setlocal enableDelayedExpansion near the top of your script. Then use !DATE!_!TIME! instead of %DATE%_%TIME%. Delayed expansion means the expansion occurs when the statement is executed, not when it is parsed. There is a good explanation in the HELP system. Type HELP SET or SET /? from a command prompt and look for the section that deals with delayed expansion.

like image 105
dbenham Avatar answered Feb 07 '23 04:02

dbenham