我正在寻找一种使用windows批处理文件的方法,它调用子批处理文件,子批处理文件传递1-9个参数和返回值(字符串),而不需要将返回值保存到文件/etc中。我将返回值保存到变量中,如@FOR /F中的did
我看着
@FOR /F "tokens=*" %%i IN ('%find_OS_version%') DO SET OS_VER=%%i
和
Call function/batch %arg1% %arg2%
我不知道如何设置才能做到这一点
编辑:dbenham稍微回答了我的问题。他的例子是在批处理文件的主体部分和函数之间。我的问题是在两个不同的批处理文件之间。基于dbenham的回答这是下面的布局。
主批处理文件
CALL sub_batch_file.bat return_here "Second parameter input"
REM echo is Second parameter input
ECHO %return_here%
REM End of main-batch file
sub_batch_file.bat
@ECHO OFF
SETLOCAL
REM ~ removes the " "
SET input=%~2
(
ENDLOCAL
SET %1=%input%
)
exit /b
REM End of sub-batch file
发布于 2012-07-15 02:09:19
通常,批处理函数以以下两种方式之一返回值:
1)使用EXIT /B n
可以通过errorlevel返回单个整数值,其中n=某个数字。
@echo off
setlocal
call :sum 1 2
echo the answer is %errorlevel%
exit /b
:sum
setlocal
set /a "rtn=%1 + %2"
exit /b %rtn%
2)更灵活的方法是使用环境变量返回一个或多个值
@echo off
setlocal
call :test 1 2
echo The sum %sum% is %type%
call :test 1 3
echo The sum %sum% is %type%
exit /b
:test
set /a "sum=%1 + %2, type=sum %% 2"
if %type%==0 (set "type=even") else (set "type=odd")
exit /b
存储答案的变量的名称可以作为参数传入!并且中间值可以对主程序隐藏。
@echo off
setlocal
call :test 1 2 sum1 type1
call :test 1 3 sum2 type2
echo 1st sum %sum1% is %type1%
echo 2nd sum %sum2% is %type2%
exit /b
:test
setlocal
set /a "sum=%1 + %2, type=sum %% 2"
if %type%==0 (set "type=even") else (set "type=odd")
( endlocal
set "%3=%sum%"
set "%4=%type%"
)
exit /b
有关最后一个示例如何工作的完整解释,请阅读DOStips上的这篇优秀的batch function tutorial。
更新
对于可以返回的内容,上述内容仍然有限制。有关支持更大范围值的基于https://stackoverflow.com/a/8254331/1012053的替代方法,请参见for。并查看https://stackoverflow.com/a/8257951/1012053中的“神奇”技术,它可以在任何情况下安全地返回长度小于~8190的任何值。
发布于 2014-08-12 01:30:08
Small TIP
Setlocal EnableDelayedExpansion
IF 1==1 (
CALL :LABEL
echo 1: %errorlevel%
echo 2: !errorlevel!
)
echo 3: %errorlevel%
:LABEL
EXIT /B 5
输出将为:
1: 0
2: 5
3: 5
EnableDelayedExpansion允许您使用!var_name!在执行时扩展var,而不是解析时。
https://stackoverflow.com/questions/11481150
复制相似问题