Home > front end >  why am I getting this bash scripting for loop error?
why am I getting this bash scripting for loop error?

Time:01-29

This is my script

#!/bin/bash
a=1
for [ $a -ge 1 ]
do
        touch ~/file.$a
        a=`expr $a   1`
done

When I execute it it gives me below error

./script.sh: line 3: syntax error near unexpected token `$a'

./script.sh: line 3: `for [ $a -ge 1 ]'

But it works fine when using "while" instead of "for".

Could you please help me understand why it works with while loop and not with for loop?

Thanks

CodePudding user response:

for loop syntax is not like that mate, do this instead.

for a in {1..10}
do
touch /file.$a
done

you need to declare the range of the variable first.

CodePudding user response:

You meant to use while not for in that syntax. Also since you're using bash, use a for (( )) loop:

for (( i = 1; i <= 10;   i )); do
    ...
done

The loop by brace expansion has also been suggested in the other answer but I'm not a fan of it since it expands iteration values to words before looping.

  •  Tags:  
  • Related