3

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

2
  • 3
    which source are you using? you can use shellcheck.net to catch typos/syntax error/etc and mywiki.wooledge.org/BashGuide is a good source for learning bash scripting
    – Sundeep
    Commented Jul 17, 2016 at 5:13
  • 3
    indenting your code is a good way to make your script more readable, and especially to get a visual overview of the structure of the code. Indent by two or four spaces or a tab each time your code enters a new control structure (like if or a case statement, or after the do in a while or for) and un-indent by the same amount whenever that ends (e.g. fi or esac or done). You can also split long lines with a \ at the end of line (not needed if the line ends with a | pipe character) - indent continued lines too. whitespace is free, use it to make your code readable.
    – cas
    Commented Jul 17, 2016 at 11:14

3 Answers 3

7
  • 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
2

The problem is in the "if" before

http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

I guess you want something like:

#!/bin/bash
echo -n "Enter a number : "
read number
echo $number

if [ $number -gt "0" ]  ; then
  ind="$number"
  while [ $ind -ge "1" ]  ; do
     echo $ind   
    ((ind--))
  done
fi
2

Well you might want to take a look at

man index

A corrected version of your script works if you replace the variable name

#!/bin/bash

echo -n Enter a number

read num

   if (($num > 0))  ; then

      ind=$num

      while [ $ind -ge 1 ]  ; do

         echo $ind

         ((ind--))

         break
         done
   fi 
1
  • 3
    Could you please indent your code? It makes it easy to read.
    – user14755
    Commented Jul 17, 2016 at 6:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .