Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm trying to call this shell script from within the CLI of GRASS GIS:

for (( day=5; day<367; day+5 )); do
  # commands that I've tested without a loop.
done
exit 0

returns

Syntax error: Bad for loop variable
share|improve this question
    
try day+=5 Good luck. –  shellter May 18 '12 at 19:49
add comment

3 Answers 3

up vote 2 down vote accepted

Perhaps GRASS GIS pre-defines a variable named "day"?

The code doesn't work in straight bash by the way. You don't actually increment the value of "day".

#!/bin/bash
for (( day=5; day<367; day=day+5 )); do
  # commands that I've tested without a loop.
        echo $day
done
exit 0

That works for me, bash 2.05b on a RHEL 5.0 server.

share|improve this answer
    
can also use day+=5 –  glenn jackman May 16 '12 at 18:41
    
OT: @glenn jackman bash 2.05b? That is a release from 2003. Anyways the sniplet does work on 4.2 too. –  jippie May 16 '12 at 19:22
    
It looks like the problem may have been using #!/bin/sh at the top of the script, as in the examples on the GRASS wiki, rather than #!/bin/bash. That, and using day+=5, does it. –  dericke May 16 '12 at 23:38
add comment

This error message comes from ash. There are several shells with a similar syntax. Ash is a relatively basic one designed for a small memory footprint and fast execution. Another common shell is Bash. Bash has more features. The syntax you posted exist only in bash (and some other shells, but not ash).

In ash, you would need to write¹:

day=5
while [ $day -lt 367 ]; do
  …
  day=$((day + 5))
done

Note that depending on the Linux distribution, /bin/sh is either ash or bash (a few exotic ones may use other implementations). If you're writing a script that uses bash syntax, be sure to put #!/bin/bash at the top.

¹ Assuming you meant day+=5 where you wrote day+5, otherwise it's an infinite loop.

share|improve this answer
    
For this case, I decided to stick with the bash solution given by Bruce, but your answer was also very helpful. Both of you caught my ash/Bash mixup. –  dericke May 30 '12 at 18:29
add comment

Would this work better?

for day in $(seq 5 5 367); do
    # commands
    echo $day
done
share|improve this answer
1  
seq is a highly nonstandard command. Don't use it. –  Chris Down May 16 '12 at 20:18
    
Totally! Thanks for pointing out. –  janos May 17 '12 at 6:30
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.