1

How can i get the current path in .cmd file?

I see a ton of people saying

oh just use "cd"

To get the value of cd , I have to set it first, which i can't as i am making it portable.

I wonder if there is any built-in variable which tell the current path of .cmd script file

like:

(C:\test.cmd)
echo %cur-path%
>> C:\

I've been searching for the internet for an hour and I can't find a solution others then "cd", "%cd".

A simple "no" will be acceptable

Coding Noob
  • 33
  • 1
  • 7
  • 1
    `current path` = `working folder` = `%cd%`. A batch file shows the folder where it is stored with `%~dp0`. See `call /?` or `for /?` to learn more about those modifiers. – Stephan Jun 27 '21 at 06:38
  • For the future: You don't want to know the __application path__ which would be `%SystemRoot%\System32` containing `cmd.exe` processing a batch file nor the __current directory path__ of the `cmd.exe` process which can be referenced with `%CD%` and does not end with a backslash except the current directory is the root directory of a drive as you want the __batch file path__ which is referenced with `%~dp0` (drive and path of argument 0 which is always the batch file itself) and always ends with a backslash. – Mofi Jun 27 '21 at 08:01
  • Does this answer your question? [What does %~dp0 mean, and how does it work?](https://stackoverflow.com/questions/5034076/what-does-dp0-mean-and-how-does-it-work) See also: [What is the reason for batch file path referenced with %~dp0 sometimes changes on changing directory?](https://stackoverflow.com/questions/12141482/) and [What is the current directory in a batch file?](https://stackoverflow.com/questions/4419868/) – Mofi Jun 27 '21 at 08:02

1 Answers1

1

Put this code in your .cmd script file(save as whatevername.cmd):

echo %~dp0

Now run it in cmd:

directory of .cmd script file\whatevername.cmd

Pretend that the .cmd script file was in C:\Users\User\Documents folder. Then the output will be:

C:\Users\User\Documents\

I hope this is what you were looking for.

Stephan
  • 53,940
  • 10
  • 58
  • 91
  • Do you know that the usage of `echo %~dp0` can result in unexpected execution behavior? A __not__ harmful example: Open a command prompt window, run `md "temp & dir"` and `>"temp & dir\test.cmd" echo echo %~dp0` to create a batch file with name `test.cmd` in directory `temp & dir` and run the batch file with `"temp & dir\test.cmd"`. There is first output the command line after expansion of `%~dp0` and next two commands: `echo` __AND__ `dir`. Run `rd /q /s "temp & dir"` to delete the temporary directory with the batch file. A string with `%~dp0` should be always enclosed in `"`. – Mofi Jun 30 '21 at 17:28