Thursday, April 19, 2007

Working Directory Independence for Batch Files


(or: Many times your batch file will want to access resources in the same folder as the batch file. This can be tricky if the user calls the batch file from another folder, since the working directory is not the directory the batch file is in. Rather that resorting to pushd / popd everywhere, one can use the extended command line parameter handling to convert the full path to the batch file into a relative path to it’s container. %0 is the path the batch was called with, so %~p0 is the path to that location)


Matt Aasted said...

Use %~pd0 instead if you want it to specify which disk as well, otherwise it will break if you're running the script from a different disk.

piers7 said...


In fact what I'd been doing subsiquent to this post is wrapping most scripts in a pushd %~dp0 / popd pair. That way script resources can be accessed even when the script was executed via double-click from a file share (many commands won't take a UNC path, but pushd will).

But then I discovered Powershell...

Eric said...

Thanks! Helped me make a yui compressor batch file. (which compresses javascript files on my W: drive)

cd %~p0
java -jar yuicompressor-2.4.2.jar --type js -v -o %1-compressed.js %1

Popular Posts