Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 282
AnthonyM Avatar asked Jul 10 '12 17:07

AnthonyM


2 Answers

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
like image 175
Elwood Avatar answered Sep 21 '22 02:09

Elwood


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.

like image 43
Eitan T Avatar answered Sep 23 '22 02:09

Eitan T