How to implement nested do while loops in windows batch file?
Here is my attempt but it keeps giving error -
set /a "x = 1"
echo %x%
:while1
if %x% leq 3 (
set /a "y = 1"
开发者_如何学Python :while2
if %y% leq 4 (
echo %y%
set /a "y = y + 1"
goto :while2
)
echo %x%
set /a "x = x + 1"
goto :while1
)
Error - G:\A>set /a "x = 1" G:\A>echo 1 1 The syntax of the command is incorrect.
There are multiple problems.
1- The %y% doesn't work as expected, as it is expanded in the moment of parsing the parenthesis block, before it is executed.
if %x% leq 3 (
set /a "y = 1"
if %y% leq 4 (
...
Expands to
if 1 leq 3 (
set /a "y = 1"
if leq 4 (
...
You better use the delayed expansion !y!
2- Your syntax error is a result of a "First-Line-Label" just before a closing parenthesis. Labels are allowed in parenthesis bocks, but they should always used in double lines.
3- goto-jumps always cancel all parenthesis blocks This isn't a problem in your case, but in the most cases it isn't a good idea, to use goto's in a block
@echo off
setlocal enabledelayedexpansion
set /a "x = 1"
echo %x%
:while1
if %x% leq 3 (
set /a "y = 1"
:while2
:while2 This is the Second-Line-Label
if !y! leq 4 (
echo y=!y!
set /a "y = y + 1"
goto :while2
)
echo x=!x!
set /a "x = x + 1"
goto :while1
)
精彩评论