Capturing the current directory from a batch file

Raymond Chen

Sometimes people go to great lengths to get information which is available in a much simpler way. We saw it a few days ago when we found a 200+-line C# program that could be replaced with a 90-byte batch file. Here’s another example of a rather roundabout way of capturing the current directory from a batch file.

The easy way is to use the %CD% pseudo-variable. It expands to the current working directory.

set OLDDIR=%CD%
.. do stuff ..
chdir /d %OLDDIR% &rem restore current directory

(Of course, directory save/restore could more easily have been done with pushd/popd, but that’s not the point here.)

The %CD% trick is handy even from the command line. For example, I often find myself in a directory where there’s a file that I want to operate on but… oh, I need to chdir to some other directory in order to perform that operation.

set _=%CD%\curfile.txt
cd ... some other directory ...
somecommand args %_% args

(I like to use %_% as my scratch environment variable.)

Type SET /? to see the other pseudo-variables provided by the command processor.

0 comments

Discussion is closed.

Feedback usabilla icon