Cd command used to change directory in DOS command line. This post talks about getting a directory path in batch programming.

Sometimes, We want to run files in the current directory in batch programming.

Get Current Directory in the batch file

%cd% variable in batch file returns current working directory with full path

test.bat file is declared b:\work directory

@echo off
echo %cd%

By running test.bat from the command line, it prints b:\work

This returns the current working directory

@echo off
echo %cd%
echo %~dp0
echo %~dpnx0

Output:

b:\work
b:\work\
b:\work\test.bat

%~dp0 returns the current director structure followed by \

%~dpnx0 returns current directory structure + name of the running batch file.

How to append the filename to the current directory in the Batch file?

It is easy to append filename in the current directory structure

@echo off
echo %cd%\notes.txt

Output:

b:\work\notes.txt

Also, You can add filenames to the current directory to a variable using set command

@echo off
set current=%cd%\notes.txt
echo %current%

Output:

b:\work\notes.txt

Run another bat file from the current working directory?

This is a simple batch code to run another batch file from the current working directory. We can also use .exe files in place of another batch file.

@echo off
cls
Echo Running other.bat
start %cd%/other.bat
exit

The above code do the following things

  • First, Clear screen using
  • Next, print the string message
  • Next line, open new window and runs other.bat file located in the current directory
  • Finally, Exit from the command line.