简体   繁体   中英

Cannot set argument value to a variable resulting empty in Windows batch script

I'm looping through all command-line arguments using SHIFT . I'm getting result of ECHO is off. . It is likely printing the empty variable.

:argLoopStart
    SET paramName=
    SET arg=%1
    IF -%arg%-==-- GOTO argLoopEnd
    IF %arg:~0,2%==-- (
        SET paramName=%arg%
        ECHO %arg%
        ECHO %paramName%
    ) 
    SHIFT
    GOTO argLoopStart
:argLoopEnd

By running the command fake-command --dbs=mydbname , I got this:

--dbs
ECHO is off.

According to the code above, ECHO %arg% prints --dbs and ECHO %paramName% prints ECHO is off . The line of SET paramName=%arg% is not working as I expected. %parameName% should print --dbs as well. However, it seems printing an empty variable.

You need to enable delayed expansion with SETLOCAL EnableDelayedExpansion at the top of your script:

Delayed Expansion will cause variables to be expanded at execution time rather than at parse time, this option is turned on with the SETLOCAL command. When delayed expansion is in effect variables may be referenced using !variable_name! (in addition to the normal %variable_name% )

@echo off
setlocal enabledelayedexpansion

:argLoopStart
set paramName=
set arg=%1
if -!arg!-==-- goto argLoopEnd
if %arg:~0,2%==-- (
    set paramName=!arg!
    echo !arg!
    echo !paramName!
)
shift
goto argLoopStart

:argLoopEnd

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