-1

I want to know how solve this:

rem declaring variable
set "vara="
echo vara:%vara% bef
call :myroutine
echo vara:%vara% aft

:routine
rem ...
rem assing value to variable vara
set "vara=34"
echo vara was assigned...
rem ....
echo vara:%vara%
exit /b

Now I have this later:

vara: bef
vara was assigned
vara:34
vara: aft

I need to use the value after of routine, like this...

vara: bef
vara was assigned
vara:34
vara:34 aft

vara:34 aft How to do it?

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85

1 Answers1

1

That's what happens already, assuming you call the correct label. (:myroutine != :routine). There are a couple of other minor issues with your script (missing goto :EOF before :routine, and doing @echo off and setlocal). Here it is fixed:

@echo off
setlocal
rem declaring variable
set "vara="
echo vara:%vara% bef
call :routine
echo vara:%vara% aft

set "vara="
goto :EOF

:routine
rem ...
rem assing value to variable vara
set "vara=34"
echo vara was assigned...
rem ....
echo vara:%vara%
exit /b

For more information about calling subroutines / functions, see this page, paying special attentions to the sections regarding different methods of returning values. What you're describing in your question already works like you want unless you setlocal within your :routine.

rojo
  • 24,000
  • 5
  • 55
  • 101
  • is there difference using goto :EOF exit /b? . . what advantage i have using setlocal? –  Nov 21 '14 at 18:56
  • For this script, there's no difference between `goto :EOF` and `exit /b`. The only real difference between the two is that `exit /b` allows you to set `%ERRORLEVEL%` to a non-zero value if you wish. See [this page](http://www.robvanderwoude.com/exit.php) for more information. Using `setlocal` prevents your script from junking up your operating environment with variables that are only relevant to the script. Without `setlocal`, `%vara%` will remain defined after the script exits -- or it would without the `set "vara="` line, anyway. This is usually unwelcome unless done intentionally. – rojo Nov 21 '14 at 19:57