It seems both can get the current directory. What is the difference between %~dp0 and %CD%, then?
- First, %~dp0 can only be used in bat file while %CD% can be used on command line.
- Second, for %CD%, the current directory means the directory when executing the command line or the batch file. For %~dp0, the current directory is the directory where the bat file resides. So if you put the batch file in c:\dir\test.bat and the file contains @echo %CD%, if you are now in C:\dir and execute test.bat, it will output c:\dir; if you are in c:\ and execute c:\dir\test.bat, it will output c:\. If the bat file has the content @echo %~dp0, whether you are in c:\ and execute c:\dir\test.bat, or in c:\dir and execute test.bat, the output is the same: c:\dir\. Note there is a back slash at the end.
If you like my content, please consider buying me a coffee. Buy me a coffee Thank you for your support!