views:

86

answers:

4

Hi I am getting parameters from user ./inputControl.sh param1 param2 ... I want users can only enter numbers. can not enter any words, etc.

if they enter word i will show them error.

thanks for answers

A: 

I don't know how you could do this easily. I would use perl or python scripting that provides regexp, it would be easier.

Aif
+2  A: 

Bash has half-decent support for regular expressions

#!/usr/bin/bash
param1=$1
param2=$2

number_regex="^[0-9]+$"

if ![[ $param1 ]] || [[ $param1 !~ $number_regex ]] ; then
    echo Param 1 must be a number
    exit 1
fi
if ![[ $param2 ]] || [[ $param2 !~ $number_regex ]] ; then
    echo Param 2 must be a number
    exit 1
fi

If you can also accept floating point numbers, then you could set number_regex to something like:

"^[+-]?[0-9]+\.?[0-9]*$"

or

"^[+-]?[0-9]+\.?[0-9]*([eE][+-]?[0-9]+)?$"

(last two regexes are untested and may not be quite right).

mobrule
And `"^[+-]?[0-9]+$"` to allow negative integers
mobrule
thanks for your good answer
FTI
I can't find any reference to `!~` and it doesn't work in my Bash 3.2. Your `if` statements can be rewritten and simplified to look like: if `[[ ! param1 || ! $param1 =~ $number_regex ]]`.
Dennis Williamson
A: 

example: check for numbers

$ echo 1234d | awk '{print $0+0==$0?"yes number":"no"}'
no
$ echo 1234 | awk '{print $0+0==$0?"yes number":"no"}'
yes number
ghostdog74
your answer simple and logical and working :) thank you
FTI
A: 

Bash regular expressions are handy, but they were only introduced in 3.1 and changed quoting rules in 3.2.

[[ 'abc' =~ '.' ]]  # fails in ≤3.0
                    # true in  =3.1
                    # false in ≥3.2
                    #   except ≥4.0 with "shopt -s compat31"
[[ 'abc' =~ . ]]    # fails in ≤3.0
                    # true in  ≥3.1

And they aren't even necessary in the first place! expr has been a standard shell utility with regex support for forever, and is works on non-GNU and non-Bash systems. (It uses basic (old) regular expressions like grep, not extended (new) regular expressions like egrep.)

expr 'abc' : '.'        # outputs '1' (characters matched), returns 0 (success)
expr 'abc' : '.\(.\).'  # outputs 'b' (group matched), returns 0 (success)
expr 'abc' : ....       # outputs '0', returns 1 (failure)
ephemient