Zach
Zach

Reputation: 75

Updating a variable inside a loop in bash shell

Everytime I run this script, it prints 0 and then aborts with the error

./hw4_1: line 6: syntax error near unexpected token `let'
./hw4_1: line 6: `  let COUNTER=0'

Source:

#!/bin/bash
COUNTER=0
echo $COUNTER
for i in {$@:2}do
  let COUNTER=0
  while [COUNTER -ne $1]; do
      echo "$i"
      let COUNTER+=1
    done;
done
exit

I've tried getting rid of let and adding a dollar sign before COUNTER, but no combination of those things work... This bash syntax is killing me. Changing 'let COUNTER=0' to COUNTER=0 just returns the error

./hw4_1: line 6: syntax error near unexpected token `let'  
./hw4_1: line 6: `  let COUNTER=0'

Upvotes: 0

Views: 1298

Answers (2)

rici
rici

Reputation: 241701

You need a semicolon (or newline) after the value list in the for statement:

for i in "${@:2}"; do

I also added the quotes because you probably want them (but maybe not).

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 224864

There's no need to use let. Just use:

COUNTER=0

You will need $COUNTER elsewhere, for example:

while [ $COUNTER -ne $1 ]

and to do the increment:

COUNTER=$(($COUNTER + 1))

Upvotes: 0

Related Questions