Search code examples
windowsbatch-filecmd

Assigning to a reference variable in batch


I've been running into a bizarre issue with batch functions/subroutines where assigning to a reference variable will work as expected, but will always print out an error saying "The syntax of the command is incorrect."

Here is an example batch script:

@echo off
setlocal enabledelayedexpansion

set Foo=1
call :JustAFunction Foo
echo %Foo%

:JustAFunction
set %1=Bar
goto :eof

endlocal

And its output:

C:\Users\Thane\Desktop>test.bat
Bar
The syntax of the command is incorrect.

Why does this happen, and what is the proper syntax?


Solution

  • You needed "goto :EOF" in the end; otherwise it will try to execute :JustAFunction code (batch doesn't stop because it encounters a function)

    @echo off
    setlocal enabledelayedexpansion
    
    set Foo=1
    call :JustAFunction Foo
    echo %Foo%
    
    
    goto :EOF
    rem ^^^^^^^^^^^^^^ you need line above.
    
    :JustAFunction
    set "%1=Bar"
    goto :eof
    
    endlocal