0

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?

Thane
  • 372
  • 4
  • 8
  • 2
    Does this answer your question? [switch-case running weird in Batch File](https://stackoverflow.com/questions/58796814/switch-case-running-weird-in-batch-file) Specifically, see my answer about how the script runs the function twice because there's no `exit /b` where you expect the script to stop running, so when it enters `:JustAFunction` a second time, `%1` is unset and the script tries to run `set =Bar`, which is a syntax error. – SomethingDark Jun 27 '21 at 15:27

1 Answers1

1

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