Could not execute a Bash Script if / while

I would like if someone points out mistakes in my script. The source where I’m learning from is so buggy that’s why it’s confusing me.

PURPOSE OF THIS SCRIPT: It will count the numbers from whatever number the user enters to number 1

#!/bin/bash

echo -n Enter a number

read number

if (($number > 0))  ; then

index = $number

while [ $index => 1 ]  ; do

echo $index

((index--))



break
done
fi    

ERROR IT GIVES: index: command not found

Answer

  • index = $number cannot use spaces around = for variable assignment.. use index=$number or ((index = number))
  • [ $index => 1 ] I suppose you want to check if index is greater than or equal to 1, use [ $index -ge 1 ] or ((index >= 1))
  • why is the break statement used? it is used to quit loop
  • also the if statement is not required
  • you can also use read -p option to add message for user

putting it all together:

#!/bin/bash

read -p 'Enter a number: ' number

while ((number >= 1)) ; do
    echo $number
    ((number--))
done

Leave a Reply

Your email address will not be published. Required fields are marked *