从另一个或提示符调用 Windows 批处理文件的几种方法。在哪种情况下调用哪个?

可以通过几种方式从另一个批处理文件(caller.batcaller.cmd)或交互式 cmd.exe 提示符调用 Windows 批处理文件(called.batcalled.cmd) :

  1. 直拨电话: called.bat
  2. 使用调用命令: call called.bat
  3. 使用 cmd 命令: cmd /c called.bat
  4. 使用 start 命令: start called.bat

我很难根据帮助文本区分它们的预期用法: 什么时候使用哪一个?例如,为什么我可以使用‘ call’命令而不是直接调用。有什么不同吗?

我对一些摘要报告感兴趣,这些报告从不同的角度分析了所有4种可能性(以及其他可能性(如果有缺失的话) : 推荐的用例,它们被设计为适合的用例,流程生成,执行上下文,环境,返回代码处理。

注意: 我使用的是 WindowsXPSP3。

57863 次浏览
  1. The batch file will be executed by the current cmd.exe instance (or a new cmd.exe instance if, for instance, double-clicked in Explorer).

  2. Same as #1, only has an effect when used inside a batch/cmd file. In a batch file, without 'call', the parent batch file ends and control passes to the called batch file; with 'call' runs the child batch file, and the parent batch file continues with statements following call.

  3. Runs the batch file in a new cmd.exe instance.

  4. Start will run the batch file in a new cmd.exe instance in a new window, and the caller will not wait for completion.

One thing not clear from the comments here: When you call one batch file from another by using just its name (Case #1 in the original question), execution stops from the calling batch file. For example, in these lines:

called.bat
echo Hello

The 'echo Hello' line (and anything following it) will not be called. If you use the 'call' keyword, execution resumes after the call. So in this case:

call called.bat
echo Hello

The 'echo Hello' line will be called.

Additionally, all the variables set in the called.bat file will be passed along back to the calling process, too.

Imagine a 'called.bat' file that had this line:

set MYVAR=hello

Then, %MYVAR% would be available to the calling batch file if it used:

call called.bat

But, it would not be using

REM starts a new cmd.exe process
start called.bat


REM stops and replaces current cmd.exe process with a new one
called.bat