Home > Enterprise >  Batch File - Why set variable inside Foreach break the loop?
Batch File - Why set variable inside Foreach break the loop?

Time:11-02

i have a problem. Here my code:

set listPath=1 2  
for %%n in (%listPath%) do ( 
    setlocal enabledelayedexpansion
    IF "!ver!"=="" (
        :loop
        echo Insert Version:
        set /p "ver="
        IF "!ver!"=="" ( 
            echo Invalid!
            Timeout /T 1 /NoBreak>nul
            goto loop
        ) ELSE (
            goto Next
        )
        :Next
    )
    echo ver: !ver!
    pause > nul
)

Because it does not work? Each time I execute the first loop and then exit the foreach ending the execution. If, on the other hand, I omit the set / p everything works normally and cycles the set well. Why? How can I go about putting that user input into the loop without breaking the loop? Thanks

CodePudding user response:

I think you are overcomplicating things for yourself, let me show you why I say that:

the choice command will force you to only select one of the options. It does not allow any other choices, other than what is in the list:

@echo off
choice /c 12 /m "Select version"
echo Ver: %errorlevel%

You already have the %errorlevel% variable which you can use to reflect as version, but you can assign that to your ver variable, if you really wanted as well:

@echo off
choice /c 12 /m "Select version"
set "ver=%errorlevel%"
echo Ver: %ver%

Other than making it that simple, your current code has numerous issues.

  1. You do not have your if and else statements correctly formatted. run from cmd if /? to see the correct syntax.
  2. You cannot goto inside of a for loop parenthesized block
  3. Your label position is invalid. the first command it sees after label is ) which is an invalid command.
  4. The for loop is not even needed and makes no sense to be honest.

If you however wanted to still use your overcomplicated version, then this will be a better version:

@echo off
set "listPath=1 2"
set ver=
:loop
set /p "ver=Insert Version: "
if not %ver% equ 1 if not %ver% equ 2 (
  echo Invalid!
  Timeout /T 1 /NoBreak>nul
  goto :loop
)
echo ver: %ver%
pause>nul
  • Related