0

I'm trying to set values in a Windows batch file, it's not working, and I have no idea why. Here's my code:

@echo off
setlocal EnableDelayedExpansion

set idx=-1
set STRING_LIST=

for %%v in (string1 string2 string3) do (
    set /A idx+=1
    echo [!idx!] %%v

    set STRING_LIST[!idx!]=%%v
)

:: Why is my list empty here??
echo STRING_LIST= %STRING_LIST%
pause

Any help would be greatly appreciated... thanks in advance!

0

2 Answers 2

1

I think I just answered my own question. First, I shouldn't have been setting the STRING_LIST array at the beginning of my script. Second, I needed to fix how I was trying to display the list item values.

Here's the final script I ended up with

@echo off
setlocal EnableDelayedExpansion enableextensions

set idx=-1

echo Populate the list:
for %%v in (string1 string2 string3) do (
    set /A idx+=1
    echo [!idx!] %%v

    set STRING_LIST[!idx!]=%%v
)
echo.

echo Individual list item values:
echo %STRING_LIST[0]%
echo %STRING_LIST[1]%
echo %STRING_LIST[2]%
echo.

echo All list item values:
for /L %%f in (0,1,!idx!) do (echo !STRING_LIST[%%f]!)
echo.

pause
Sign up to request clarification or add additional context in comments.

2 Comments

Just a note to mention that as your final value of the variable named idx was set within another code block, you don't need to delay it's expansion outside of that block. Instead of (0,1,!idx!) you could have used (0,1,%idx%).
Great, thank you for pointing that out. I was definitely coding fast and loose in trying to get things to work. =P
1

I know you've solved your issue, (you were trying to show the values of a previously undefined variable instead of the ones you were after). This is simply to expand upon the advice in my now deleted comment regarding undefining any existing STRING_LIST[… variables and showing all those newly defined at the end, as that is what I think you were trying to do.

@For /F "Delims==" %%A In ('Set STRING_LIST[ 2^>NUL')Do @Set "%%A="
@Set "idx=-1"
@For %%A In (string1 string2 string3)Do @(Set /A idx+=1
    Call Echo [%%idx%%] %%A&Call Set "STRING_LIST[%%idx%%]=%%A")
@Set STRING_LIST[ 2>NUL&&Pause||Exit /B

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.