Abdallah Qaraeen
Abdallah Qaraeen

Reputation: 113

How to make a batch file sleep for some time inside an if statement?

I am trying to write the below code, and I want it to display the error before it exits, but whenever I run it, it exits right away.

@echo off
cd "haha"
if %errorlevel% 1 (
   echo Failure reason given is %errorlevel%
   sleep 5
   exit /b %errorlevel%
)
echo files deleted successfully!
del /Q *
pause

I have also tried timeout /t 5 doesn't seem to work.

Upvotes: 3

Views: 1914

Answers (2)

Magoo
Magoo

Reputation: 80033

The correct syntax is

if errorlevel 1 (

meaning if errorlevel is 1 or greater

OR

if %errorlevel% geq 1 (

which means the same thing.

As it stands, cmd is interpreting you code as

if 1 1 (

(assuming errorlevel is 1). This is a syntax error, so cmd shows a message. If you are running by point-click and giggle, the window will close. If you are running from the prompt, then cmd will report a syntax error.

Be warned however that executing an exit statement from the prompt will abort the cmd instance. Better to use goto :eof unless you have good reason otherwise.

timeout /t 5 should work, but will generate a countdown.

timeout /t 5 >nul should appear simply to wait. The issue is that you have to solve the if syntax first, else the timeout instruction won't be reached.

Upvotes: 3

SachaDee
SachaDee

Reputation: 9545

This should work :

@echo off
cd "haha" 2>nul
if %errorlevel%==1 (
   echo Failure reason given is %errorlevel%
   timeout /t 5
   exit /b %errorlevel%
)

Upvotes: 3

Related Questions