0
echo off

set /a a=0
:start
if %a% LEQ 21(
echo test
set /a a=%a%+1
goto start
)

I don't get it... I only get a Syntax-error when the loop starts.

1
  • 2
    This is not BASH syntax, it's a mashup of Microsoft CMD syntax. Commented Nov 16, 2012 at 10:09

3 Answers 3

2

The code you posted isn't a valid bash script it's a batch script to echo test 20 times in a bash script using a for loop like this:

#/bin/bash

for i in {1..20}; do
    echo test
done

Much clearer and readable than batch scripts, welcome to bash!

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

1 Comment

sorry, changed that, my fault. faster typing than thinking often result in stupid mistakes.
2

Besides the error already explained by Bali C, you should note that your code have a potential problem. In this command: set /a a=%a%+1 the %a% value is expanded just one time when the if command is executed. In this case your code run by chance because the goto command cause the if be executed again in each loop, but if your program would be larger and more complex, and this set command would be executed several times inside parentheses, the code would fail because %a% will be expanded just one time to the value that a variable had before enter the parentheses.

The way to solve this problem is easy in this case: just eliminate the percent signs, because set /a a=a+1 command can directly take the values of the variables. However, there is much more involved here! For further details, type set /? and pay attention to "delayed variable expansion" description.

Comments

0

You are missing a space between 21 and ( which will make it compare the number in the loop to 21(, also breaking the if statement, the latter being why you are getting a syntax error.

Add a space and it works fine.

echo off

set /a a=0
:start
if %a% LEQ 21 (
echo test
set /a a=%a%+1
goto start
)

Comments

Your Answer

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