如何将变量从一个批处理文件传递到另一个批处理文件?

Jon*_*hai 11 batch-file

如何编写获取输入变量并将其发送到另一个批处理文件以进行处理的批处理文件.

批次1

我不知道如何将变量发送到批处理2,这是我的问题.

批次2

if %variable%==1 goto Example
goto :EOF

:Example
echo YaY
Run Code Online (Sandbox Code Playgroud)

Iva*_*van 13

你根本不需要做任何事情.批处理文件中设置的变量在它调用的批处理文件中可见.

test1.bat

@echo off
set x=7
call test2.bat
set x=3
call test2.bat
pause
Run Code Online (Sandbox Code Playgroud)

test2.bat

echo In test2.bat with x = %x%.
Run Code Online (Sandbox Code Playgroud)

产量

...当test1.bat运行时.

In test2.bat with x = 7.
In test2.bat with x = 3.
Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)


Som*_*ark 12

您可以将batch1.bat变量作为参数传递给batch2.bat.

arg_batch1.bat

@echo off
cls

set file_var1=world
set file_var2=%computername%
call arg_batch2.bat %file_var1% %file_var2%

:: Note that after batch2.bat runs, the flow returns here, but since there's
:: nothing left to run, the code ends, giving the appearance of ending with
:: batch2.bat being the end of the code.
Run Code Online (Sandbox Code Playgroud)

arg_batch2.bat

@echo off

:: There should really be error checking here to ensure a
:: valid string is passed, but this is just an example.
set arg1=%~1
set arg2=%~2

echo Hello, %arg1%! My name is %arg2%.
Run Code Online (Sandbox Code Playgroud)

如果需要同时运行脚本,可以使用临时文件.

file_batch1.bat

@echo off
set var=world

:: Store the variable name and value in the form var=value
:: > will overwrite any existing data in args.txt, use >> to add to the end
echo var1=world>args.txt
echo var2=%COMPUTERNAME%>>args.txt

call file_batch2.bat
Run Code Online (Sandbox Code Playgroud)

file_batch2.bat

@echo off
cls

:: Get the variable value from args.txt
:: Again, there is ideally some error checking here, but this is an example
:: Set no delimiters so that the entire line is processed at once
for /f "delims=" %%A in (args.txt) do (
    set %%A
)

echo Hello, %var1%! My name is %var2%.
Run Code Online (Sandbox Code Playgroud)