arraysbatch-file

Why batch ECHO does not work with a array value using the %%i as index in for loops?


I am remaking vim (and calling vin.bat because it might be awful) but batch isnt echoing the result.

i tried doing this:

@echo off

setlocal enableDelayedExpansion
set "lines[0]=base"
set "choices= qwertyuiopasdfghjklzxcvbnm"

:start

for %%i in (%lines%) do (
    echo line: %%i
)

set /p choice=" "  >nul

echo %choice%

goto start

set "choice=!choices:~%errorlevel%,1!"

i thougth it would work just fine. but it didnt.

%%i is outputting an error. (ECHO is disabled error i know what it is), the loop does nothing, and it just outputs the %choice% value and sometimes a space character.


Solution

  • There is no variable named lines, hence the for loop is interpreted as

    for %%i in () do (
    

    likely the cause of your error.

    Use

    for /f "delims=" %%i in ('set lines[ 2^>nul') do (
    

    to have %%i set to the value of each variable whose name starts lines[ in turn. The 2^>nul suppresses the error message produced should there be no variables whose name starts lines[. 2 means stderr , > is a redirector to the nul device and the caret escapes the redirector, telling the parser that the redirector is part of the set command, not the for.

    Note also that set delivers the variable names in alphabetical order,so it would output lines[0], lines[1], lines[10], lines[11], lines[2], lines[3] ...

    You could use

    for /L %%i in (0,1,99) do if defined lines[%%i] echo !lines[%%i]!
    

    to overcome this.

    See for/? from the prompt or endless items on SO for documentation.

    choice is a poor selection for a variable name, since it is a command name in cmd.

    See choice/? from the prompt or endless items on SO for documentation.

    Your code simply loops back to start so there is no way of reaching the final set command.