子功能上的奇怪批处理文件行为

时间:2013-11-07 22:39:09

标签: batch-file

以下代码我希望在命令窗口中打印出两行代码。为什么要打印3行?

@echo off


call:myDosFunc1 100 YeePEE
goto:yyy


:myDosFunc1    - here starts my function identified by it`s label
echo. it could do %~1 of things %~2.
:yyy



call:myDosFunc2 100 YeePEE
goto:ttt


:myDosFunc2   - here starts my function identified by it`s label
echo. it could do %~1 of things %~2.

:ttt

2 个答案:

答案 0 :(得分:3)

删除@echo off行并在末尾添加pause命令,您可以观察脚本所采用的流程。问题背后的原因是您没有从:myDosFunc1返回,因此代码会落到myDosFunc2,意味着:myDicFunc2被调用两次。

简单修复,将以下内容添加到myDosFunc1

:myDosFunc1    - here starts my function identified by it`s label
echo. it could do %~1 of things %~2.
goto:eof
:yyy

建议:像这样构建脚本以防止工作流问题。

@echo off

call:myDosFunc1 100 YeePEE
call:myDosFunc2 100 YeePEE
exit /b 0

:myDosFunc1    - here starts my function identified by it`s label
echo. it could do %~1 of things %~2.
exit /b 0

:myDosFunc2   - here starts my function identified by it`s label
echo. it could do %~1 of things %~2.
exit /b 0

答案 1 :(得分:1)

问题在于,与CDelphi或其他语言不同,其中过程名称是显式的并且到达过程的末尾意味着返回,批处理就像汇编程序一样,其中标签只是标记。到达标签什么都不做 - 无论如何批量收费。如果返回堆栈耗尽,则到达文件结尾(或使用内置GOTO :EOF隐式返回或终止。EXIT /b是显式返回,也可以选择设置errorlevel