batch-file

Commenting via REM and :: doesn't work in batch script


I just want to leave a reminder about the %~ symbol combination, but my running my batch file outputs this:

C:\Users\batch\batch>add_one2The following usage of the path operator in batch-parameter
substitution is invalid: %~n' is passed argument
For valid formats type CALL /? or FOR /?
C:\Users\batch\batch>

Here's the script:

@echo off
REM '%~n' is passed argument
goto :main

:add_one
setlocal
    echo  Running 'add_one'...
endlocal & set /a %~1=%~2+1
goto :eof

:main
setlocal
    set /a x=1
    set /a y=50
    
    echo Created variable X and set it to %x%
    echo.
    call :add_one y %y%
    echo.
    echo The value of X is now %x%
endlocal
goto :eof

I tried ::, REM, and escaping in quotes, but it didn't work either.


Solution

  • Parameter expansion happens before other commands (see How does the Windows Command Interpreter (CMD.EXE) parse scripts? for much more detail), so the interpreter is trying to expand %~n before the REM command tells it that that line is a comment. Because argument-style variables must contain a digit, you will always get an error when you only use a letter.

    For better information, use the actual variables in the function header documentation:

    @echo off
    goto :main
    
    REM ===================================================
    REM Arguments: %1 - The name of the variable to store
    REM                 the value in
    REM            %2 - The value to add
    REM ===================================================
    :add_one
    setlocal
        echo  Running 'add_one'...
    endlocal & set /a %~1=%~2+1
    goto :eof
    
    :main
    setlocal
        set /a x=1
        set /a y=50
        
        echo Created variable X and set it to %x%
        echo.
        call :add_one y %y%
        echo.
        echo The value of X is now %x%
    endlocal
    goto :eof