4

Possible Duplicate:
How do I test if a variable is a number in bash?

I try writing the fibonacci sequence by shell scripting for example if user entered 5 after the script name in the command line the script needs to print out the 5 fibonacci numbers from the beginning which are:

0 1 1 2 3 

I have completed the script but I need to check the user input if it is positive number that I have a problem in this part. in the command line the user should call the script and then enter a positive number

./script number

and this is my code:

#!/bin/sh
[ $# -ne 1 ] && { echo "enter a number please" ; exit 1 ; } 
[ ! echo $1 | egrep -q '^[0-9]+$' &&  $1 -lt 0  ] && { echo "negative" ; exit 1 ; }

f0=0
f1=1
counter=2
if [ $1 -eq 0 ] ; then
echo -n "0"
elif [ $1 -ge 1 ] ; then
    echo -n "0 1" 
fi
    while [ $counter -le $1 ] && [ $1 -gt 1 ] ; do
        echo -n "$fn "      
        fn=`expr $f0 + $f1`
        f0=$f1
        f1=$fn
        counter=`expr $counter + 1`
    done 
echo ""
Community
  • 1
  • 1
femchi
  • 1,185
  • 8
  • 20
  • 37

2 Answers2

4
if [ $1 -ge 0 2>/dev/null ] ; then

it works for positive numbers equal or greater than 0

femchi
  • 1,185
  • 8
  • 20
  • 37
-2

Take a look at this:

http://www.bashguru.com/2010/12/how-to-validate-integer-input-using.html

Apparently someone wrote multiple shell scripts to do exactly that.

sampson-chen
  • 45,805
  • 12
  • 84
  • 81
  • it works but if you enter a letter in the input it gives you an error about comparing a letter by 0 – femchi Oct 30 '12 at 20:55
  • 1
    The linked page is infested with auto-forwarding ads. Don't visit unless you're feeling unstoppable. – bassim Sep 22 '15 at 11:27