AnthonyM
AnthonyM

Reputation: 1145

How do I return a value from a function in a batch file?

I have the following batch file

@echo off
setlocal EnableDelayedExpansion
for /f "delims==" %%J in (File_List.txt) do (
call :setDate %%J MYD
echo/Date is: %MYD%
)
endlocal &goto :eof

:setDate
SETLOCAL ENABLEEXTENSIONS
echo %1
echo %~2
set NAME=%1
set NAME=%NAME:~-11%
echo %NAME%
echo %~2
endlocal&set %2=%NAME%&goto :eof

but with File_List.txt containing file2012-05.csv

I get

file2012-05.csv
MYD
2012-05.csv
MYD
Date is:

How do I actually get the function setDate to return the value I want?

Upvotes: 23

Views: 58390

Answers (3)

Bret
Bret

Reputation: 1

Would you wonderful folks validate this answer to the question? Obviously I'm very new, but I need to solve this problem too:

@echo off

REM define and print debug output for a variable
set a_variable_populated_by_a_function=not useful
@echo on
echo %a_variable_populated_by_a_function% is not useful :(
@echo off

REM call the function, pass in our variable
call :a_function a_variable_populated_by_a_function

REM pointer to where function is complete
:a_function_complete
goto :resume_code

REM function definition
SetLocal
    :a_function
        set %1=so very useful!
        goto :a_function_complete
EndLocal


REM pointer to resume life after function stuff
:resume_code

REM print debug output for variable altered by function
@echo on
echo %a_variable_populated_by_a_function% is so useful :O
@echo off

my output is

not useful is not useful :(
so very useful! is so useful :O

Would the best solution to the question "How do I return a value from a function in a batch file?" require three separate labels / pointers?

:a_function
:a_function_complete
:resume_code

Or maybe these scripts are so messy that "whatever works, works."

Upvotes: 0

Elwood
Elwood

Reputation: 357

As I don't understand from your script what you want to achieve, I reply (for completeness) to the original subject: returning a value from a function.

Here is how I do it:

@echo off

set myvar=
echo %myvar%
call :myfunction myvar
echo %myvar%
goto :eof

:myfunction
set %1=filled
goto :eof

Result is:

empty 
filled

Upvotes: 34

Eitan T
Eitan T

Reputation: 32930

The batch interpreter evaluates %MYD% at parse time, and at that time it's empty. That's why you have Delayed Expansion. Change this line:

echo/Date is: %MYD%

to this:

echo/Date is: !MYD!

and it will work like you want, because then it tells the interpreter to evaluate MYD at run-time.

Upvotes: 25

Related Questions