- What is the current directory in a batch file?
- 9 Answers 9
- %__CD__% , %CD% , %=C:%
- Get current batchfile directory
- 4 Answers 4
- Create folder in batch script and ignore if it exists
- 2 Answers 2
- Create folder with batch but only if it doesn’t already exist
- 9 Answers 9
- BAT file to open CMD in current directory
- 18 Answers 18
What is the current directory in a batch file?
I want to create a few batch files to automate a program.
My question is when I create the batch file, what is the current directory? Is it the directory where the file is located or is it the same directory that appears in the command prompt, or something else?
9 Answers 9
From within your batch file:
dp0 refers to the full path to the batch file’s directory (static)
%
f0 both refer to the full path to the batch directory and file name (static).
dp0 will always give the full path to the executing batch file. – dbenham Jun 12 ’13 at 11:19
dp0 gives the full path to the directory that the executing batch file is in. %
dpnx0 (which is equivalent to %
f0) gives the full path to the batch file. See robvanderwoude.com/parameters.php for more details. – deadlydog Jul 11 ’13 at 20:08
dp0 is the working directory not the batch files directory, Found this out the hard way. – trampster Jan 29 ’18 at 22:44
dp0 gives the batch file directory with trailing slash. – icc97 Feb 27 ’18 at 9:10
It usually is the directory from which the batch file is started, but if you start the batch file from a shortcut, a different starting directory could be given. Also, when you’r in cmd, and your current directory is c:\dir3 , you can still start the batch file using c:\dir1\dir2\batch.bat in which case, the current directory will be c:\dir3 .
In a batch file, %cd% is the most commonly used command for the current directory, although you can set your own variable:
So say you were wanting to open Myprog.exe. If it was in the same folder, you would use the command:
That would open Myprog from the current folder.
The other option is to make a directory in C: called AutomatePrograms. Then, you transfer your files to that folder then you can open them using the following command:
dp0 is more consistent. – icc97 Feb 27 ’18 at 9:14
Say you were opening a file in your current directory. The command would be:
I hope I answered your question.
It is the directory from where you run the command to execute your batch file.
As mentioned in the above answers you can add the below command to your script to verify:
It is the directory from where you start the batch file. E.g. if your batch is in c:\dir1\dir2 and you do cd c:\dir3 , then run the batch, the current directory will be c:\dir3 .
Just my 2 cents. The following command fails if called from batch file (Windows 7) placed on pendrive:
But this does the job:
dp0 – Ammar Mohammad Aug 3 ’19 at 12:49
%__CD__% , %CD% , %=C:%
There’s also another dynamic variable %__CD__% which points to the current directory but alike %CD% it has a backslash at the end. This can be useful if you want to append files to the current directory.
With %=C:% %=D:% you can access the last accessed directory for the corresponding drive. If the variable is not defined you haven’t accessed the drive on the current cmd session.
Get current batchfile directory
Firstly, I saw this topic but I couldn’t understand that.
Question :
There is a batch file in D:\path\to\file.bat with following content :
It must be D:\path\to
What am I doing wrong?
4 Answers 4
System read-only variable %CD% keeps the path of the caller of the batch, not the batch file location.
You can get the name of the batch script itself as typed by the user with %0 (e.g. scripts\mybatch.bat ). Parameter extensions can be applied to this so %
dp0 will return the Drive and Path to the batch script (e.g. W:\scripts\ ) and %
f0 will return the full pathname (e.g. W:\scripts\mybatch.cmd ).
You can refer to other files in the same folder as the batch script by using this syntax:
This can even be used in a subroutine, Echo %0 will give the call label but, echo «%
nx0″ will give you the filename of the batch script.
When the %0 variable is expanded, the result is enclosed in quotation marks.
dp0 will return path to batch location. echo %
f0 will return path to the batch with filename. – Stoleg Jun 12 ’13 at 12:03
dp0 ? – Ivailo Bardarov May 5 ’17 at 10:06
dp0 as first line of batch file and worked – mkb Oct 25 ’17 at 4:03
dp0″ rather than %
dp0 . Quotes will guarantee the path is taken as one token, even if there are spaces, and also protects against poison characters like & . – dbenham Dec 20 ’19 at 3:53
Within your .bat file:
You can now use the variable %mypath% to reference the file path to the .bat file. To verify the path is correct:
For example, a file called DIR.bat with the following contents
run from the directory g:\test\bat will echo that path in the DOS command window.
Here’s what I use at the top of all my batch files. I just copy/paste from my template folder.
Setting current batch file’s path to %batdir% allows you to call it in subsequent stmts in current batch file, regardless of where this batch file changes to. Using PUSHD allows you to use POPD to quickly set this batch file’s path to original %batdir%. Remember, if using %batdir%ExtraDir or %batdir%\ExtraDir (depending on which version used above, ending backslash or not) you will need to enclose the entire string in double quotes if path has spaces (i.e. «%batdir%ExtraDir»). You can always use PUSHD %
dp0. [https: // ss64.com/ nt/ syntax-args .html] has more on (%
Note that using (::) at beginning of a line makes it a comment line. More importantly, using :: allows you to include redirectors, pipes, special chars (i.e. | etc) in that comment.
Of course, Powershell does this and lots more.
Create folder in batch script and ignore if it exists
How do I create folder(and any subfolders) in batch script? What is important, if folder(or any subfolders) already exists, it should not return error.
For example, something like this:
- mkdir mydir — success(directory is now created)
- mkdir mydir\subdir — success(now mydir contains subdir )
- mkdir mydir — success(folder already exists, should not throw an error)
- mkdir mydir\subdir — success(folders already exists, should not throw an error)
What I actually need is just to ensure that folders structure exists.
2 Answers 2
A standard method to create a directory structure is:
By default command extensions are enabled and delayed expansion is disabled. The batch code above explicitly sets up this environment.
The command MD creates the complete directory structure to specified directory with enabled command extensions.
MD outputs an error if the directory already exists. This might be useful to inform a user entering the command manually about a possible mistake in entered directory path as it could be that the user wanted to create a new directory and has entered just by mistake the name of an already existing directory.
But for scripted usage of command MD it is often a problem that this command outputs an error message if the directory to create already exists. It would be really helpful if command MD would have an option to not output an error message in case of directory to create already existing and exiting with return code 0 in this case. But there is no such option.
The solution above creates the directory and suppresses a perhaps output error message with redirecting it from handle STDERR to device NUL.
But the creation of the directory could fail because of invalid character in directory path, drive not available (on using full path), there is anywhere in path a file with name of a specified directory, NTFS permissions don’t permit creation of the directory, etc.
So it is advisable to verify if the directory really exists which is done with:
It is important that the directory path ends now with \* or at least with a backslash. Otherwise it could be possible for the example that there is a file with name subdir 2 in directory mydir\subdir 1 which on usage of the condition if not exist «%Directory%» would evaluate to false although there is no directory subdir 2 .
It is of course also possible to do the directory check first and create the directory if not already existing.
The user can see now the error message output by command MD if the directory structure could not be created explaining briefly the reason.
This batch code could be written more compact using operator || :
For details about the operators || and & read the answer on Single line with multiple commands using Windows batch file.
The command ENDLOCAL is not used before goto :EOF because this command requires also enabled command extensions. Windows command interpreter executes this command implicit on leaving execution of the batch file.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
Read also the Microsoft article about Using Command Redirection Operators.
Create folder with batch but only if it doesn’t already exist
Can anybody tell me how to do the following in in a Windows batch script? ( *.bat ):
- Create a folder only if it doesn’t already exist
In more detail, I want to create a folder named VTS on the C:\ drive, but only if that folder doesn’t already exist. I don’t want to overwrite the contents of the folder if it already exists and the batch is executed.
9 Answers 9
You just use this: if not exist «C:\VTS\» mkdir C:\VTS it wll create a directory only if the folder does not exist.
Note that this existence test will return true only if VTS exists and is a directory. If it is not there, or is there as a file, the mkdir command will run, and should cause an error. You might want to check for whether VTS exists as a file as well.
Just call mkdir C:\VTS no matter what. It will simply report that the subdirectory already exists.
Edit: As others have noted, this does set the %ERRORLEVEL% if the folder already exists. If your batch (or any processes calling it) doesn’t care about the error level, this method works nicely. Since the question made no mention of avoiding the error level, this answer is perfectly valid. It fulfills the needs of creating the folder if it doesn’t exist, and it doesn’t overwrite the contents of an existing folder. Otherwise follow Martin Schapendonk’s answer.
BAT file to open CMD in current directory
I have many scripts which I interact with from the command line. Everytime I need to use them, I have to open a command line window and copy+paste and CD to the path to the directory they are in. This is tedious (they are in a rather deep file system, so typing out the full path is a pain, copy+paste is better but not much). I tried to create a .BAT file that I could double-click on that would open a new command-line window in the folder the .bat file exists in but it does not work. It opens a new window, but the working directory is not the directory that .bat file is in. Here’s what I’ve got after much googling (My cmd skills ain’t so great):
I know from when I used Linux that Konqueror had a «Command-line window here» feature, and that’s the effect I’m trying to get on Windows.
18 Answers 18
Create a file named open_dos_here.cmd with the following lines:
Put this file at any folder. Then, go to your Send To folder ( Win + E ; Alt + D ; shell:sendto ; Enter ). Create a shortcut to point to this open_dos_here.cmd
Then, in any folder, select any file or sub-folder. Right-click and select «Send To» and then select open_dos_here.cmd to open the DOS in that folder.
p1″ – Alvin SIU Dec 19 ’10 at 15:33
d1 is to extract only the drive letter of %1 (e.g. C:). This goes to C drive. The 2nd line cd to %
p1 which is the path of %1 (i.e. \myFolder). After going to this directory, simply call the cmd to open the DOS command prompt. – Alvin SIU Aug 23 ’14 at 9:12
you probably want to do this:
this will set your current directory to the directory you have the batch file in
dp0′ is simply the variable that holds the path the currently executing batch file is located in — therefore executing this command will take you to that directory (apparently this variable is only available from a batch file, which makes sense) – Chris Dec 15 ’10 at 15:51
dp0″ With the double-quotes? – Paul Tomasi Dec 19 ’10 at 3:59
dp0′ – Chris Jan 11 ’11 at 15:23
You can just enter cmd into the address bar in Explorer and it starts up in that path. Likewise for PowerShell.
There’s more simple way
As a more general solution you might want to check out the Microsoft Power Toy for XP that adds the «Open Command Window Here» option when you right-click: http://www.microsoft.com/windowsxp/downloads/powertoys/xppowertoys.mspx
In Vista and Windows 7, you’ll get that option if you hold down shift and right-click (this is built in).
I’m thinking that if you are creating a batch script that relies on the Current Directory being set to the folder that contains the batch file, that you are setting yourself up for trouble when you try to execute the batch file using a fully qualified path as you would from a scheduler.
Better to add this line to your batch file too:
unless you are fully qualifying all of your paths.
The simplest command to do this:
start
You can always run this in command line to open new command line window in the same location. Or you can place it in your .bat file.
Most simple way in explorer is to Shift + right mouse click on the folder or on an empty space in the folder and click on Open command prompt here .
CMD will then start in that folder
I must say, I’m not sure if it works for Windows Vista and below, but it surely works for Windows 7, 8, 8.1 and 10.
Another solution is to use a shortcut file to cmd.exe instead of a batch file.
Edit the shortcut’s start in property to %
You achieve the same thing, except it has the Cmd icon (and you can change this).
Some people don’t like clicking on batch files without knowing what’s in them, and some corporate network drives have a ban on .bat files.
You could add a context menu entry through the registry:
Navigate in your Registry to HKEY_LOCAL_MACHINE/Software/Classes/Folder/Shell and create a key called «Command Prompt» without the quotes.
Set the default string to whatever text you want to appear in the right-click menu.
Create a new key within your newly created command prompt named «command,» and set the default string to
You may need to add %SystemRoot%\system32\ before the cmd.exe if the executable can’t be found.
- The changes should take place immediately. Right click a folder and your new menu item should appear.
Referring to answer of @Chris,
We can also go to parent directory of batch file and run commands using following
To understand working of command cd /d %
dp0.. please refer below link
A bit late to the game but if I’m understanding your needs correctly this will help people with the same issue.
Two solutions with the same first step: First navigate to the location you keep your scripts in and copy the filepath to that directory.
- Click «Start»
- Right-click «Computer» (or «My Computer)
- Click «Properties»
- On the left, click «Advanced System Settings»
- Click «Environment Variables»
- In the «System Variables» Box, scroll down and select «PATH»
- Click «Edit»
- In the «Variable Value» field, scroll all the way to the right
- If there isn’t a semi-colon (;) there yet, add it.
- Paste in the filepath you copied earlier.
- End with a semi-colon.
- Click «OK»
- Click «OK» again
- Click «OK» one last time
You can now use any of your scripts as if you were already that folder.
Second Solution: (can easily be paired with the first for extra usefulness)
On your desktop create a batch file with the following content.
This will open a command window like what you tried to do.