0

I am trying to run a bash script like so:

#!/bin/bash

set i=1991

while [ $i -le 2017 ]
do
    echo "looping and doing stuff"
    $i++
done
echo all done

I get the following error:

[: -le: unary operator expected

I have also tried changing the code like so:

 #!/bin/bash

set i=1991


while (( $i <= 2017 ));
do
    echo "looping";
    (( $i++ ));
done

echo ALL done

which gives me this error:

((: <= 2017 : syntax error: operand expected (error token is "<= 2017 ")

and I've tried this:

#!/bin/bash

set i=1991

while [ "$i" -le "2017" ]
do
    echo "looping"
    $i++
done

echo ALL done

And I get this:

[: : integer expression expected

I think it's a stupid syntax error but unfortunately I can't seem to figure it out. My version of bash is 4.3.48.

Thank you!

1
  • 1
    shellcheck points out many such common syntax errors Commented Sep 19, 2018 at 18:12

1 Answer 1

1

set is used to set the positional parameters, not ordinary variables.

$ unset i
$ set i=1991
$ echo "$1"
i=1991
$ echo "$i"

$

The i=1991 is a single argument to set, treated as a literal string, not an assignment of any kind.

Just drop the set:

i=1991
while (( i < 2017 )); 
  ...
  ((i++))
done
Sign up to request clarification or add additional context in comments.

1 Comment

You might also have a echo "$i" in there, just to show that it's empty (if an unset i is added as a first line).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.