0

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
4
  • @abhi1610, you are taking "a" as counter but incrementing "n" !!! huhhhh Commented May 6, 2016 at 11:52
  • @anubhava Thank you for your info about the link. By your answer you would just print the numbers not iterate them. I want to iterate over the while loop. Commented May 6, 2016 at 11:54
  • @monk Thank you for spotting the typo error. Commented May 6, 2016 at 11:55
  • 2
    Iterate: for n in {1..5}; do echo "$n"; done Commented May 6, 2016 at 11:56

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the answer. For the curiosity can you describe why we can't use <= instead -lt?
its for integer comparison
You can use <= if you use the arithmetic statement: while (( a <= 5 )); do. bash doesn't have data types (all values are strings), so you need special commands and operators to specify whether you want to do string operations or treat the strings as integers.
1

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

1 Comment

Thanks for the descriptive answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.