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
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
I don't know how you could do this easily. I would use perl or python scripting that provides regexp, it would be easier.
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).
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
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)