Command line .cmd/.bat script, how to get directory of running script

后端 未结 3 1003
北海茫月
北海茫月 2021-01-30 15:26

How can you get the directory of the script that was run and use it within the .cmd file?

3条回答
  •  感情败类
    2021-01-30 16:20

    Raymond Chen has a few ideas:

    https://devblogs.microsoft.com/oldnewthing/20050128-00/?p=36573

    Quoted here in full because MSDN archives tend to be somewhat unreliable:

    The easy way is to use the %CD% pseudo-variable. It expands to the current working directory.

    set OLDDIR=%CD%
    .. do stuff ..
    chdir /d %OLDDIR% &rem restore current directory

    (Of course, directory save/restore could more easily have been done with pushd/popd, but that's not the point here.)

    The %CD% trick is handy even from the command line. For example, I often find myself in a directory where there's a file that I want to operate on but... oh, I need to chdir to some other directory in order to perform that operation.

    set _=%CD%\curfile.txt
    cd ... some other directory ...
    somecommand args %_% args

    (I like to use %_% as my scratch environment variable.)

    Type SET /? to see the other pseudo-variables provided by the command processor.

    Also the comments in the article are well worth scanning for example this one (via the WayBack Machine, since comments are gone from older articles):

    http://blogs.msdn.com/oldnewthing/archive/2005/01/28/362565.aspx#362741

    This covers the use of %~dp0:

    If you want to know where the batch file lives: %~dp0

    %0 is the name of the batch file. ~dp gives you the drive and path of the specified argument.

提交回复
热议问题