0

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

1
  • DO you need to accept floats or just ints? Commented Nov 3, 2009 at 22:15

4 Answers 4

2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

And "^[+-]?[0-9]+$" to allow negative integers
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 ]].
0

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

Comments

0

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)

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.