Mark Needham

Thoughts on Software Development

Getting the current working directory from DOS or Batch file

with 23 comments

In the world of batch files I’ve been trying for ages to work out how to get the current/present working directory to make the batch script I’m working on a bit more flexible.

In Unix it’s easy, just call ‘pwd’ and you have it. I wasn’t expecting something that simple in Windows but it is! A call to ‘cd’ is all that’s needed. If you need to set it in a batch script the following line does the trick:


set WORKING_DIRECTORY=%cd%

I was surprised that something so simple (I do now feel like an idiot) wasn’t easier to find on Google. I ended up going via Experts Exchange (how they end up with such high search results when you have to pay to see the information is beyond me) and several other verbose ways of solving the problem before finally coming across this article which explained it.

Be Sociable, Share!

Written by Mark Needham

August 12th, 2008 at 10:37 pm

Posted in Batch Scripting,Build

Tagged with ,

  • You don’t have to pay to view the Experts Exchange answers, you just have to scroll past all the bogus “Subscribe to see this answer” boxes
    It’s tedious, but it’s all there at the bottom 🙂

    HTH

  • Oh yeah! Wow I totally didn’t realise that was the case. I always saw the massive ‘Sign up now to view this solution’ and immediately pressed the back button or just didn’t bother going to the page in the first place.

    Thanks for that though, useful to know.

  • Reshmi

    Hi Thanks,Very useful info!

  • David

    Before knowing what Andy wrote, I was super annoyed with Experts Exchange because they come up on the top of Google searches. I was wishing there was a default Google filter I could set, e.g. -site:”Experts Exchange”, but no more!

    Mark, Thanks for the tip on the Current Working Directory for DOS.

  • anonymous

    Everywhere its always the same, I’ve searched and searched using every possible wording I can think up. The above is all that ever comes up or some variant thereof. All I want returned or used in my batch file is just the folder name itself not the whole damn path.

    I have been trying in vain to create a simple batch file that will start at whichever directory I execute it in and search through all it’s subdirectories for any files and rename them all to match the name of the folder they reside in. I already know how to set up everything to rename all the files in all the directories sequentially.

    I just can’t believe xp’s cmd.exe doesn’t have a simple way of taking just the folder name itself [not the whole path] and making it available as a string to use for whatever, like providing a prefix for renaming files in this case. Gawd this is frustrating! It is so damn simple in UNIX. Why does XP have to be so friggan difficult???

  • Adam Pond

    I guess you are after a cheat sheet…

    Ok… you owe me one.

    If you are looking for the current working directory, you can use %cd%.

    Alternatively, you can try tackling the problem in a different way by passing the directory you want to use in as an argument and referencing it with %1

    For example:
    MyBatchFileWithAPath.bat “C:\temp”

    Also, if you are after the directory where the script lives, try %~dp0
    (obvious isn’t it?)

    Finally, if you want to know the full path of the batch file, it is the first argument (index 0), ie %0

    Try writing the following batch file:
    echo Current dir = %CD%
    echo Script dir = %~dp0
    echo Batch path = %0
    echo User argument 1 = %1

    As for why it has to be so difficult, I’m not sure I can answer that one 🙂

  • Ben Luplow

    %~dp0
    That is what I have been looking for! Thank you so much! Why the ef was that so convoluted and hidden from any sort of help menu?

  • Ben Luplow

    Now when our corp changes the directory paths all around I won’t have to edit 200 scripts!

  • Ron Patrick

    What Adam posted let me to this additional (obvious -NOT) piece of info:

    For the drive where the batch file lives, use %~d0
    For just the directory path where the batch file lives, use %~p0

    i.e.
    echo Current Drive = %~d0
    echo Current Path = %~p0

  • SenHu

    I always loved DOS-batch because it provided open-ended possibilities. I came from UNIX world and so appreciated its openness of interface ( not everything was wrapped tight in a GUI box). I have been using DOS for a while. I think though these days biterscripting has been replacing DOS pretty quickly. There are some excellent sample scripts posted at http://www.biterscripting.com. I still reamain a fan of DOS, but, must admit, tend to use biterscripting more and more these days. Also, sometimes, DOS just does not provide the functionality that I need, such as, redirecting the output to a string variable, easy date calculation, string parsing, stream editors, etc. That’s when I have no choice but to use biterscripting.

  • Thanks @Adam. Your instructions helped to create custom print folder bat file.

  • Ben Luplow

    For a complete list of the variable commands type for /? in cmd and they are all a few pages down.
    In addition, substitution of FOR variable references has been enhanced.
    You can now use the following optional syntax:

    %~I – expands %I removing any surrounding quotes (“)
    %~fI – expands %I to a fully qualified path name
    %~dI – expands %I to a drive letter only
    %~pI – expands %I to a path only
    %~nI – expands %I to a file name only
    %~xI – expands %I to a file extension only
    %~sI – expanded path contains short names only
    %~aI – expands %I to file attributes of file
    %~tI – expands %I to date/time of file
    %~zI – expands %I to size of file
    %~$PATH:I – searches the directories listed in the PATH
    environment variable and expands %I to the
    fully qualified name of the first one found.
    If the environment variable name is not
    defined or the file is not found by the
    search, then this modifier expands to the
    empty string

    The modifiers can be combined to get compound results:

    %~dpI – expands %I to a drive letter and path only
    %~nxI – expands %I to a file name and extension only
    %~fsI – expands %I to a full path name with short names only
    %~dp$PATH:I – searches the directories listed in the PATH
    environment variable for %I and expands to the
    drive letter and path of the first one found.
    %~ftzaI – expands %I to a DIR like output line

    In the above examples %I and PATH can be replaced by other valid
    values. The %~ syntax is terminated by a valid FOR variable name.
    Picking upper case variable names like %I makes it more readable and
    avoids confusion with the modifiers, which are not case sensitive.

  • Agostino

    Many thanks, it works!

  • Scott D

    Thank you for your article. I also found these 2 commands below were good for finding the current directory and making it come up in Notepad, so you can copy and paste it:
    cd > filepath.txt
    filepath.txt | more

  • Mark

    Still no way to get JUST the current directory name, not the full path! 🙁

  • Jon

    %0! Who knew? Thanks @Adam.

    This page is still coming up in searches so, I’ll just add that if you want just the current folder, you’ll have to extract it from the path yourself:
    (you’ll need delayed expansion enabled for this)

    call :getCurrentFolder “%~1” strPath

    :getCurrentFolder
    setlocal
    set ret=%~1
    if “!ret!” equ “” (
    set ret=
    ) else if “!ret:~-1!” equ “\” (
    set ret=
    ) else (
    call :getCurrentFolder “!ret:~0,-1!” folder
    set ret=!folder!!ret:~-1!
    )
    endlocal&set %2=%ret%

  • Mike Vasiljevs

    many a million ben.

    Problem: use xcopy without File/Directory prompt

    e.g. entry is “dirfile.txt”, discard filename to get “dir”

    Solution:

    given 

    source_dir = “d:source”

    and

    target_dir = “c:tmpsource”

    script below
    —————-
    set some_file_entry=dirfile.txt
    set dst_file=%target_dir%%some_file_entry%

    for %%f in (%dst_file%) do (
        xcopy %source_dir%%some_file_entry% %%~df%%~pf
    )
    ————————
    will copy:

    “d:sourcedirfile.txt” -> “c:tmpsourcedirfile.txt”

    without “(F = file, D = directory)? ” bullsh*t!!!

  • Chupakabra

    Once more with feeling…

    Now take the case of a WinCE device not providing delayed expansion and not providing FOR either (welcome to hell)

    only %0 is mainly available here.

    The only solution I could see is the following:
    – get the %0
    – MKDIR a folder with some added characters to your batch filename (nasty)
    – CD  NEWDIR..
    – RMDIR NEWDIR

    This is awfull but provides a solution, no need to say it’s not even reliable if you are on a ReadOnly partition (pretty rare within this context imho).

    any comments on this?

  • llbbl

    awesome thanks!

  • Pratap Reddy

    This is one of the useful post.
    I wanted to copy the assembly from one folder to another folder without any knowledge of location of the parent folder. All i needed to do is as below
    COPY /Y “%cd%Folder1Folder2Folder3binDebugaaAutoControlIdentifierLib.dll” “%cd%Dlls”

  • veggen

    Just needed this and your post helped. Thanks!

  • Peeramid

    Well, if a batch script is called from a .pif file then the following do not work:
    setlocal
    %0
    %~anything
    %cd%

    One can pass a fixed string parameter (D:path) on the .pif command line, but not an environment name such as %CD%.

    Then there is the FOR statement:
    SET PWD=$$
    FOR %%V IN (/%2) DO IF %PWD%==$$ SET PWD=%%V:
    The logical test in the IF clause is executed once even though DO performs the IF … SET twice!?

    %HOMEDRIVE% and %SySTEMDRIVE% are in the environment, for what it’s worth.

    I agree with SenHu about the open possibilities of DOS batch programming as opposed to the closed world of Unix and Linux, but Win7 security has thrown up some barriers.

    If a Batch program is called by a .pif from a shared drive, and it tries to call a local script, say %HOMEPATH%DESKTOPSETPRINT.BAT or %SYSTEMDRIVE%SETPRINT.BAT, then Win7 blocks the call. (Maybe this was in the virtual mode only, but it doesn’t matter.) A CD to the local drive has to be performed first, but then one has to get back to the original directory.

    I tried a simple solution: pass the PWD as parameter %2 of my program call. Then the statements

    %SYSTEMDRIVE%
    SETPRINT.BAT
    CD /D %2

    returned the final insult: “Invalid switch – /D”.

  • Matt Nelson

    I just found this over at superuser.com:

    for %%* in (.) do set CurrDirName=%%~n*
    echo %CurrDirName%