Harsh Makadia
Harsh Makadia

Reputation: 3443

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.

Upvotes: 2

Views: 3004

Answers (2)

Compo
Compo

Reputation: 38614

Your script unnecessarily sets a variable to the name of an existing variable before setting a variable which is not used at all. It then deletes all of the files in the current tree before removing all of the directories, when removing the directories alone should do it.

The following single line batch script should do the same as your script and only do so if the location exists!

@CD /D "%__CD__%Mac\Data" 2>Nul && RD /S /Q "%__CD__%Mac\Data">Nul 2>&1

The command following the && operator is only ran if the command immediately prior to it returned as successful.

Upvotes: 0

Magoo
Magoo

Reputation: 80023

@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.

Upvotes: 3

Related Questions