'why am I getting this bash scripting for loop error?
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
Solution 1:[1]
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.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Faizawa |
| Solution 2 | konsolebox |
