Saturday 26 April 2008

Batch Programming Tip #02: Using cd /D

Using the /D option on the CD command is another very simple "trick" which can come in handy if you're not sure what the final location of your script will be or whether it will actually be stored on the same drive as where you want the working directory to be.

(Note: the CD command is used to Change Directory. It can be really useful in combination with the FOR loop as we will see in a later tip.)

On a two-drive computer (we'll call the drives C:\ and D:\, in our examples), try the following.

On drive C:\ create a batch file containing:

@echo off
cd D:\DirectoryName
echo Current location: %cd%
echo Press any key to exit...
pause > NUL


Although you have changed directories on the D:\ drive, you will find the %cd% variable still contains the drive path on drive C:\.

(Note: The %cd% variable expands to your current working directory. It's mostly considered like an environment variable, meaning you don't have to set it, it just "exists" natively.)

This is where the /D option comes in handy as it forces a drive change too, if necessary.

@echo off
:: change directory and force drive change
cd /D D:\DirectoryName
echo Current location: %cd%
echo Press any key to exit...
pause > NUL

This second example works because it also changes the drive letter automatically so you can now move your script to a different location on a different drive and still obtain the expected results.

In the following script we will save the original location, switch to a new working directory and then back to the original location once we have finished doing Some Really Useful Stuff. The script is a little more complicated and contains calls to a subroutine and also uses of the famous black hole both of which we'll get back to later on.

@echo off

:init_vars
SET original=%cd%
SET working=D:\DirectoryName
goto do_switch

:do_switch
:: the following will show original location
call :show_cd
:: change directory and force drive change
cd /D "%working%"
:: this will now show the new working directory
call :show_cd
goto do_something

:do_something
echo This is where we put Our Really Useful Code
goto end_script

:end_script
:: switch back to original location
cd /D "%original%"
call :show_cd
goto eof

:show_cd
echo Working directory is now: %cd%
goto blackhole

:eof
echo Press any key to exit...
pause > NUL

:blackhole


So basically using cd /D is a pretty effective way of keeping things nice and simple and avoiding those last minute surprises we could all do without :).

No comments:

Online Marketing
Add blog to our blog directory blog search directory Blog Directory Blogarama - The Blog Directory