Check if the argument is a number inside the shell script

Possible duplicate:
How to check if a variable is a number in bash?

I try to write a Fibonacci sequence using shell scripts, for example, if the user entered 5 after the script name in the command line, the script should print 5 Fibonacci numbers from the very beginning, which are:

 0 1 1 2 3 

I have completed the script, but I need to check the user input, if it is a positive number, that I have a problem in this part. at the command prompt, the user must invoke 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 "" 
+4
source share
2 answers
 if [ $1 -ge 0 2>/dev/null ] ; then 

works for positive numbers equal to or greater than 0

+3
source

Take a look at this:

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

Obviously, someone wrote several shell scripts to do just that.

0
source

Source: https://habr.com/ru/post/1443095/


All Articles