【问题标题】:How do I return a variable from a called batch file to the caller?如何将被调用批处理文件中的变量返回给调用者?
【发布时间】:2017-01-19 00:07:04
【问题描述】:

我希望能够调用批处理文件,就像它是 Java 中的函数或类似的东西一样。是否有可能做一些事情,例如

set answer=call Calculate.bat %input1% %input2%

calculate.bat 将计算两个输入的总和,然后将其分配给原始批处理文件中的 answer 变量。这在某种程度上可能吗?

【问题讨论】:

  • 当你call另一个批处理文件时,它在命令解释器的当前实例中运行。因此,如果它设置了一个变量,那么在调用返回后该变量仍然会被设置。
  • 除非第二个批处理文件也有setlocal
  • this question 可能被骗

标签: windows batch-file call


【解决方案1】:

如果你像@SomethingDark 所说的那样在你的脚本中使用setlocal,你可以决定只传输某些变量

@ECHO OFF
setlocal

REM your code here, for example:
set /A "output=%1 + %2" > NUL

endlocal & set "answer=%output%"

REM variable %output% does not exist anymore
REM only %answer% remain changed (and stay the same once the script end)

【讨论】:

    【解决方案2】:

    就像@Harry johnston 所说,如果您在批处理文件中设置一个变量,您调用的变量将在调用者中设置。如果您不想在调用的批处理文件中设置任何变量,请执行以下操作:

    for /f %%a in ('calculate.bat %input1% %input2%') do set "output=%%a"
    

    命令的输出存储在%output%

    【讨论】:

    • 可能需要添加结果必须是来自calculate.batechoed 才能使用循环读取它。但我想我也会选择这个:)
    猜你喜欢
    • 2011-10-07
    • 2013-07-19
    • 2013-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-17
    • 2012-11-17
    • 2021-10-21
    相关资源
    最近更新 更多