命令行.cmd / .bat脚本,如何获取运行脚本的目录

时间:2020-03-06 14:41:26  来源:igfitidea点击:

如何获得已运行脚本的目录,并在.cmd文件中使用它?

解决方案

雷蒙·陈(Raymond Chen)有一些想法:

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

在此处完整引用,因为MSDN存档往往有些不可靠:

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.

另外,本文中的评论也值得一看,例如:

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

这涵盖了%〜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.

这等效于脚本的路径:

%~dp0

这使用批处理参数扩展语法。参数0始终是脚本本身。

如果脚本存储在C:\ example \ script.bat中,则%〜dp0的计算结果为C:\ example \

ss64.com包含有关参数扩展语法的更多信息。以下是相关摘录:

You can get the value of any parameter using a % followed by it's numerical position on the command line.
  
  [...]
  
  When a parameter is used to supply a filename then the following extended syntax can be applied:
  
  [...]
  
  %~d1 Expand %1 to a Drive letter only - C:
  
  [...]
  
  %~p1 Expand %1 to a Path only e.g. \utils\ this includes a trailing \ which may be interpreted as an escape character by some commands.
  
  [...]
  
  The modifiers above can be combined:
  
  %~dp1 Expand %1 to a drive letter and path only
  
  [...]
  
  You can get the pathname of the batch script itself with %0, parameter extensions can be applied to this so %~dp0 will return the Drive and Path to the batch script e.g. W:\scripts\

for /F "eol= delims=~" %%d in ('CD') do set curdir=%%d

pushd %curdir%

来源