How do I find the current directory of a batch file, and then use it for the path?

Ryan Barber picture Ryan Barber · Apr 27, 2013 · Viewed 171.8k times · Source

I have a batch file that I intend to distribute to our customers to run a software task.

We distribute them as a folder or .zip with the files inside. Inside, there is the batch files and another folder with the files needed to run the batch.

Normally, when you make a batch, you type the path where the files are. But I won't know where the files are. The files will still be kept inside the master folder, but I need to have the batch find that folder to run the files.

So for example: If they have the master folder on the desktop and they run it, it would need to be something like "C:\Users\Username\Desktop" to run. You would have the batch CD to that location.

But what if they run it from documents? I don't know the username, so I have to somehow have the batch find this. Any code and/or instructions would be great.

Answer

ElektroStudios picture ElektroStudios · Apr 27, 2013

There is no need to know where the files are, because when you launch a bat file the working directory is the directory where it was launched (the "master folder"), so if you have this structure:

.\mydocuments\folder\mybat.bat
.\mydocuments\folder\subfolder\file.txt

And the user starts the "mybat.bat", the working directory is ".\mydocuments\folder", so you only need to write the subfolder name in your script:

@Echo OFF
REM Do anything with ".\Subfolder\File1.txt"
PUSHD ".\Subfolder"
Type "File1.txt"
Pause&Exit

Anyway, the working directory is stored in the "%CD%" variable, and the directory where the bat was launched is stored on the argument 0. Then if you want to know the working directory on any computer you can do:

@Echo OFF
Echo Launch dir: "%~dp0"
Echo Current dir: "%CD%"
Pause&Exit