简体   繁体   中英

Windows batch file timing bug

I've used %time% for timing previously - at least I think I have. I have this weird

IF NOT "%1" == "" (
    echo Testing: %1
    echo Start: %time%
    sqlcmd -S MYSERVER  -i test_import_%1.sql -o "test_%1%.log"
    sleep 3
    echo End:   %time%
)

I run this, and it prints:

Testing: pm
Start: 13:29:45.30
End:   13:29:45.30

In this case, my sql code is failing (different reason), but I figure the sleep 3 should make the time increment by 3 at least. Any ideas? tx, tff

This has something to do with (not) delayed expansion, but I don't remember how that works exactly. You can work around it by using a "subroutine" like this:

@echo off
if "%1" == "" (
  call :doit
)

echo done
goto :eof

:doit
echo %time%
sleep 1
echo %time%
goto :eof

Output:

C:\temp>q
19:46:36.43
19:46:37.45
done

The "proper" way of doing this is probably something like (from this entry in Raymon Chen's blog ):

setlocal enabledelayedexpansion
if "%1" == "" (
  echo !time!
  sleep 2
  echo !time!
)

To "see" the problem with immediate expansion, just run this ( without echo off ):

if "%1" == "" (
echo %time%
sleep 2
echo %time%
)

Output (on Windows 7):

C:\temp>if "" == "" (
echo 19:48:31.95
 sleep 2
 echo 19:48:31.95
)
19:48:31.95
19:48:31.95

The variables are all expanded at the same time, when the if is parsed.

Pause doesn't accept a parameter at all. It won't fail, but it won't continue either. If all is right, you should see a prompt to press a key.

The time you get, is the time the script is started. Apparently the %time% environment variable is not updated during the execution of the script.

DOS doesn't have a "sleep" function. You need to add this to the end of your batch file (or something like this):

@ECHO off
TITLE Initial title
SET TITLETEXT=Sleep
:: start of script
CALL :sleep 5
:: rest of script
GOTO :END
:: Function
:sleep ARG
ECHO Pausing...
FOR /l %%a in (%~1,-1,1) do (TITLE %TITLETEXT% -- time left %%as&PING.exe -n 2 -w 1 127.0.0.1>nul)
EXIT /B 0
:END
pause
::this is EOF

I tested this code, it should work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM