May 05, 2007
No "sleep" command for batch files? Make it a choice!
I just trapped myself while hacking up a batch file.
Used to shell scripting I wanted to add a delay to the batch using “sleep”.
Dough! Bad Idea! Bad command or filename. Smash your head here to continue {(x)}!
So I winded up my memories from stoneage. Wasn’t there the choice command!?
Yeah, after some lurking around with the ‘/?’ feature I had stuck it together:
choice /c 1 /d 1 /t 1 > nul
While
- “/c 1” sets the choice values (1 is my value)
- “/d 1” sets the default choice value (which is 1 from above)
- “/t 1” sets the timeout to 1 second (or whatever is appropriate)
- “> nul” means the same as “>/dev/null”: send output to nirvana (notice there being only one ‘l’ however)
Of course this may be bothersome to type if you use it often, so a “batch function” may be better, especially when you need other batch tricks to get around DOS command limitations (lazy man’s approach: create a second batch file for it).
@echo off rem ******************* rem check args rem ******************* :checkargs if "%1/" == "func/" goto callfunc goto main :_checkargs rem ******************* rem call functions rem ******************* :callfunc shift rem we could do "goto %1" instead rem if there is a lot of functions if "%1/" == "sleep/" goto sleep goto exit :_callfunc rem ******************* rem function sleep rem ******************* :sleep shift choice /c 1 /d 1 /t %1 > nul goto exit :_sleep rem ******************* rem main body rem ******************* :main echo hello, going to sleep now call %0 func sleep 1 echo sleep is over, good bye goto exit :_main rem ******************* rem exit handler rem ******************* :exit rem if there is anything left to do, do it now. :_exit
May 31st, 2008 at 11:15 am
Hi,
Cheers for that trick. very handy.
I was wondering where did my sleep go when I switched to Vista. Your solution solved problem just right!
June 5th, 2008 at 12:19 am
Thanks Buddy. This helped me quite a bit. I was not able to use sleep in Vista.
December 16th, 2012 at 6:29 am
Nice finding !! Great 🙂