Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop batch script on del failure

Tags:

batch-file

We have a batch script that removes files (del) and directories (rd). Does anyone know how to halt (fail) execution of the script if any of these delete statements fail? They could fail if a file/directory is locked by Windows. Thanks.

Update

Statements I'm using:

Del: del *.* /S /Q

RD: FOR /D %%G in (*) DO RD /s /q %%G

like image 573
Marcus Leon Avatar asked Feb 18 '09 13:02

Marcus Leon


2 Answers

For deleting the files, you can first try to ren (rename) the file. ren will set ERRORLEVEL to 1 if the file is locked. Add quotes around filename.

@echo OFF

:: Delete all files, but exit if a file is locked.
for %%F in (*.*) do (
    @echo Deleting %%F
    ren "%%F" tmp 2> nul
    if ERRORLEVEL 1 (
        @echo Cannot delete %%F, it is locked.
        exit /b 1
    )
    del tmp
)

I suspect you may be able to do the same thing for directories, but I can't seem to figure out how to get a directory locked so I can test. The following may work:

:: Remove all directories, but exit if one is locked.
FOR /D %%G in (*) DO (
    @echo Removing %%G
    ren "%%G" tmpdir 2> nul
    if ERRORLEVEL 1 (
        @echo Cannot remove %%G, it is locked
        exit /b 1
    )
    RD /s /q tmpdir
)
like image 70
Patrick Cuff Avatar answered Jan 04 '23 13:01

Patrick Cuff


DEL doesn't return an errorlevel if the file is locked. I just did a test with excel file and I saw a zero (on Windows XP).

It might be better to use IF EXIST for the file to be deleted after you do the delete.

del file.txt
if exist file.txt ECHO "FAIL"

AFTER EDIT Disclaimer: I have no idea how this performs...

You could do this for the files

DIR /B /S /A-d > c:\filestodelete.txt

del *.* /S /Q    

FOR /F %%i in (c:\filestodelete.txt) DO (
    IF EXIST %%i ECHO %%i STILL EXISTS
)

then for the directories

DIR /B /S /Ad > c:\directoriestodelete.txt

FOR /D %%G in (*) DO RD /s /q %%G    

FOR /F %%i in (c:\directoriestodelete.txt) DO (
    IF EXIST %%i ECHO %%i STILL EXISTS
)
like image 43
Jason Punyon Avatar answered Jan 04 '23 11:01

Jason Punyon