Let's say I'm using a batch file and want it to direct to a folder located in the same directory of the batch. If I'm not wrong you would write "%~dp0\whateverfoldername". But can't the same done by just writing ".\whateverfoldername"? If so, what is the difference and/or advantage of the respective command?
The %~dp0 (that's a zero) variable when referenced within a Windows batch file will expand to the drive letter and path of that batch file. The variables %0-%9 refer to the command line parameters of the batch file. %1-%9 refer to command line arguments after the batch file name. %0 refers to the batch file itself.
~dp0 : d=drive, p=path, %0=full path\name of this batch-file. cd /d %~dp0 will change the path to the same, where the batch file resides.
The cd command, also known as chdir (change directory), is a command-line shell command used to change the current working directory in various operating systems. It can be used in shell scripts and batch files. cd / chdir.
By default, /F breaks up the command output at each blank space, and any blank lines are skipped. You can override this default parsing behavior by specifying the "options" parameter.
pushd %~dp0
is often used to change to the original directory from which the batch was started. This is very useful in newer OS's when the user may 'Run as administrator' which changes the current directory for you! Try it sometime. Just make a simple bat
@echo off
echo.CD=%CD%
pushd %~dp0
echo.CD=%CD%
pause
Now run it. Now run it again 'As Administrator' on Vista, Win 7, Win 8, 2008 Server, or 2012 Server. See what happens?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With