Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows CMD %time% giving same time when used with & operators

Tags:

cmd

I am using the following code to benchmark my script.

C:\Users\blueray>echo %time% & timeout /t 5 & echo %time%

Output

13:44:44.64
... after 5 seconds
13:44:44.64

I was expecting to have a 5 second increment when I echo %time% for the second time. What is the problem here and what is the solution?

like image 840
blueray Avatar asked Oct 16 '25 01:10

blueray


2 Answers

Windows command interpreter first preprocesses/parses the entire command line before execution. During this preprocessing all environment variable references in the form %variable% are expanded so that in your case the command line really executed is:

echo 13:44:44.64   & timeout /t 5   & echo 13:44:44.64

It is necessary to force a delayed expansion of the environment variables.

Usually delayed expansion is used in a batch file like this:

setlocal EnableDelayedExpansion
echo !TIME! & timeout /t 5 & echo !TIME!
endlocal

Or on specifying executable TIMEOUT with fully qualified file name and using immediate environment variable expansion on first TIME reference while using delayed expansion on second TIME reference:

setlocal EnableDelayedExpansion
echo %TIME% & %SystemRoot%\System32\timeout.exe /t 5 & echo !TIME!
endlocal

But there is a second method to get a delayed environment variable expansion in a batch file by using the command CALL.

echo %TIME% & %SystemRoot%\System32\timeout.exe /t 5 & call echo %%TIME%%

This command line in batch file results in executing finally the command line:

echo 13:44:44.64   & C:\Windows\System32\timeout.exe /t 5   & call echo %TIME%

The command CALL results in a second parsing of echo %TIME% before executing second ECHO resulting in getting output time about 5 seconds later than first time output.

In a command prompt window a different command line is required due to different interpreting of % in comparison to batch file processing.

echo %TIME% & timeout /t 5 & call echo ^%TIME^%

The percent sign characters are escaped with caret character ^ to be first interpreted as literal characters to finally execute call echo %TIME%. In real it is enough to escape just second % while escaping just first % has not the wanted effect on time output. So working in a command prompt window as expected is also:

echo %TIME% & timeout /t 5 & call echo %TIME^%

But not working as expected in a command prompt window is:

echo %TIME% & timeout /t 5 & call echo ^%TIME%
like image 61
Mofi Avatar answered Oct 18 '25 06:10

Mofi


A workaround

(for /F "delims=" %x in ('echo ^%time^%') do echo %x )& timeout /t 2 &(for /F "delims=" %x in ('echo ^%time^%') do echo %x)
like image 39
Nahuel Fouilleul Avatar answered Oct 18 '25 08:10

Nahuel Fouilleul