1

I want to create a utility batch file which will be consumed by client batch file. The Utility batch file will create the result & will redirect as output. The client batch file will call utility.bat & will get the result in a variable.

The code of Utility.bat I have written is as below

echo off
set result="some info"
echo %result%
rem output

I am not sure about the syntax of how to pass the result as output

The code of client.batch is as below

@echo off 
set var1=%Utility.bat%
echo "%var1%"

Need help in syntax to pass result as output.

I found many answers on web for passing result to text file (logging) but that was not my requirement.

rajesh
  • 285
  • 4
  • 16

2 Answers2

5

You need to use CALL to have one batch file call another. You can pass the name of a variable as a parameter, and the CALLed script can store the result there.

Utility.bat

@echo off
set "result=some info"
set "%~1=%result%"

Client.bat

@echo off
call utility var1
echo var1=%var1%

If Utility uses SETLOCAL, then a mechanism is needed to pass the value accross the ENDLOCAL barrier. Only the Utility needs to change:

Utility.bat

@echo off
setlocal
set "result=some info"
endlocal & set "%~1=%result%"

If the return value might contain quotes and poison characters, then a different method is needed.

Utility.bat

@echo off
setlocal enableDelayedExpansion
set result="Quoted <^&|>" and unquoted ^<^^^&^|^>
for /f delims^=^ eol^= %%A in ("!result!") do endlocal & set "%~1=%%A"

The last code above supports all characters except carriage return (0x0D) and linefeed (0x0A), and it has problems if the return value contains ! when the caller (client.bat) has delayed expansion enabled. There is a solution that eliminates the restrictions, but it is complicated. See https://stackoverflow.com/a/8257951/1012053.

Community
  • 1
  • 1
dbenham
  • 127,446
  • 28
  • 251
  • 390
  • In Utility I am using a variable which is getting processed. Can you please suggest a syntax where I can assign variable value to output. – rajesh May 06 '14 at 08:53
1

utility.bat

...
set result="some info"
call client.bat %result%
...

client.bat

...
set var1=%1
echo %var1%
....
Magoo
  • 77,302
  • 8
  • 62
  • 84
  • A utility is not supposed to call the client; "Any" (while creating utility we are not aware of any client) client can call the utility. – rajesh May 06 '14 at 08:49