简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM