Search code examples
windowsbatch-filebatch-processingcd

Check if change directory command is executed properly in batch file windows


I'm working on a batch file script where my requirement is to traverse into the folder from the current directory and delete some files.

What happens is if the path is not found it starts deleting files from the wrong location.

Here my script

set BuildPath="%CD%"
set DrivePath="%CD:~0,3%"

cd "%BuildPath%\Mac\Data\"
del * /S /Q
rmdir /S /Q "%BuildPath%\Mac\Data\"

Now what happens in the above script is if "%BuildPath%\Mac\Data\" is not found it will start deleting files from the wrong folder because the cd command did not work.

What I want to check is whether the changing directory was successful or not. if it was not successful then I don't want to perform any action.


Solution

  • @ECHO Off
    SETLOCAL
    PUSHD u:\sourcedir
    set "BuildPath=%CD%"
    set "DrivePath=%CD:~0,3%"
    
    cd "%BuildPath%\Mac\Data"
    IF ERRORLEVEL 1 ECHO fail cd
    IF /i "%cd%" neq "%BuildPath%\Mac\Data" echo FAIL&GOTO :EOF 
    ECHO del * /S /Q
    ECHO rmdir /S /Q "%BuildPath%\Mac\Data\"
    popd
    
    GOTO :EOF
    

    Note : U:\sourcedir is my test directory.

    If the cd is successful, errorlevel will be 0 so the fail cd message will not be issued. cd after the change will contain the same path as specified (I omit the trailing backslash).

    On the other hand, if the change is not successful (directory does not exist), errorlevel will become 1 and the fail cd message will be produced, and cd will not be as specified.

    So two methods here - errorlevel and compare-directory-name. This is a reason for assigning strings using set "var=value" syntax, where the number and position of rabbit's ears can be controlled.