4025Views14Replies

Author Options:

Batch file-Change the target directory to wherever the file is? Answered

I need to make a batch file change the directory to wherever it is currently stored. I know how to use the "cd" command, but I don't know how to get the current directory of the file. Can someone please help?

Discussions

hi i need help about this batch script and it drives me crazy :)
i have a batch script that installing a driver but the problem is the script only works when its inside of the source file, i want my batch file outside of the folder win32 and win64
here is my code
@echo off
rem add a new sample divice driver
@pushd %~dp0
if defined programFiles(x86) (
@echo installing the 64bit version of divice Driver
@cd %/driver/win64/%
installer.exe install installer.inf installer.sys
) else (
@echo installing the 32bit version of divice Driver
@cd %/driver/win32/%
installer.exe install installer.inf installer.sys
)
pause

Actually I asked a friend about half an hour ago. He showed me a much simpler way: %cd% returns the current working directory. So I solved the problem with "cd %cd%" for anyone else having the same problem.

.  if %cd% does what you want, that's great, but it is not equivalent to %~dp0.
.  %cd% = drive and path of current directory (may change).
.  %~dp0 = drive and path where batch file is located (can't change).

Thank you for sharing the information (although I don't really see how that's much simpler than "%~dp0")!

Try google searches using the additional keywords of "relative links".

Are you sure? The dot (.) directory is relative to the user's session, not relative to the saved location of the script (what DOS-kiddies call a "batch file").

Yes. I'm trying not to spoon-feed, but %~dp0 points to the script's current path - which information may be found in the very first hit of a Google search for "batch relative link". :)

Cool. Thanks for giving me some new information. From looking at a couple of those links, I've got to say: modern "Windoze" batch program looks even more obfuscated than Perl!

:D Tell me about it. I won't touch the cr...stuff, myself. After a *nix shell, a windows command line feels like...going back to kindergarten (particularly on the latest versions). Or like trying to complete a triathlon with no limbs.

I googled CD your way and found Nacho was my cousin, the missing link.

I don't know how to do this in DOS, but in a Real Operating System, you can always use `dirname $0` to get the directory in which the current command file is saved.