PDA

View Full Version : [SOLVED] user inputs and grep



Ristar
August 8th, 2008, 06:13 PM
hello, im trying to write something to check the validity of a user's input in bash...

how do i make the program reject alpha and special characters?

thanks.

mssever
August 8th, 2008, 07:32 PM
hello, im trying to write something to check the validity of a user's input in bash...

how do i make the program reject alpha and special characters?

thanks.

read input
if [[ $input =~ ^[0-9]*$ ]]; then
# do something
else
echo "Bad input"
exit 1
fi

Ristar
August 8th, 2008, 07:46 PM
read input
if [[ $input =~ ^[0-9]*$ ]]; then
# do something
else
echo "Bad input"
exit 1
fi


uh.... but if i press space or if no characters were entered, it'd be OK also.

is there a way to stop this?

ConMan318
August 8th, 2008, 07:52 PM
Just a small change:


read input
if [[ $input =~ ^[0-9]+$ ]]; then
# do something
else
echo "Bad input"
exit 1
fi


The '*' means to match 0 or more times, so zero number entered does match. The '+' means to match 1 or more times, so there has to be at least one digit entered to match.

Ristar
August 8th, 2008, 07:56 PM
thx guys.... that really helped.

mssever
August 8th, 2008, 07:58 PM
uh.... but if i press space or if no characters were entered, it'd be OK also.

is there a way to stop this?
Just adjust the regular expression to allow the correct characters.

ghostdog74
August 9th, 2008, 02:11 AM
hello, im trying to write something to check the validity of a user's input in bash...

how do i make the program reject alpha and special characters?

thanks.

read this (http://tldp.org/LDP/abs/html/testbranch.html) page. There are examples on testing user input. Also, although regexp in bash can be used, its only supported in newer bash (which i think you will have it.)