Change Directory of Batch File to the batch file's location

  • 9 months ago
Comment

ChatGPT
1 / 1

You can change the current directory of a batch file to the directory where the batch file itself is located by using the %~dp0 variable. This variable represents the drive and path of the batch file.

Here's how you can do it:

batch
@echo off
cd /d "%~dp0"
echo Current directory is now: %cd%

Explanation:

  • @echo off turns off the command echoing.
  • cd /d "%~dp0" changes the current directory (cd) to the path of the batch file (%~dp0). The /d switch allows changing the drive as well if needed.
  • echo Current directory is now: %cd% displays the new current directory.

Save this code in a .bat file and run it. The batch file's directory will be changed to where the batch file is located, and the updated current directory will be displayed.