abhi1610
abhi1610

Reputation: 743

Error: While loop in bash shell script

I am trying to run simple script named test.sh which echo the numbers in ascending manner. But somehow it shows error.

#!/bin/bash

clear
a= 0

while [ $a <= 5 ];
do
    echo $a
    a=$(( a+1 ))
done

Error:

./test.sh: line 4: 0: command not found
./test.sh: line 6: =: No such file or directory

Upvotes: 0

Views: 1784

Answers (2)

Jahid
Jahid

Reputation: 22448

The first problem with your code is a= 0, spaces aren't allowed (before or after =) in assignment.

secondly, this part [ $a <= 5 ]. You have to use -lt instead of <= here.

As you are already familiar with the (( )) construct, I will recommend you to use that instead, which will let you compare integers with <=, >= etc..

Your code with the above modification:

#!/bin/bash

clear
a=0

while (( $a <= 5 ));
do
    echo $a
    a=$(( a+1 ))
done

Upvotes: 1

monk
monk

Reputation: 2115

Way better is already mentioned by Anubhava, however this is correct version of your answer.

#!/bin/bash

clear
a=0

while [[ "$a" -lt 5 ]];
do
    echo $a
    a=$(($a+1))
done

Upvotes: 1

Related Questions