Click to See Complete Forum and Search --> : How to check if variable contains non numeric characters in Bash?


Hediir
10-09-2005, 04:49 PM
I need to check if a variable contains any numberic characters, how can i do that?

Programming in bash in Linux.

I am pretty new to programming :( Please help, thanks :)

Sepero
10-09-2005, 06:46 PM
I was unable to find any info on this. Perhaps a scripting language like Python may suit your needs better.

happybunny
10-09-2005, 06:51 PM
can you ls|grep [09] the names, then if $?=1 non of them contained a 0-9 character, right?

Sepero
10-09-2005, 07:47 PM
Borrowing from happybunny, I suppose you could try something like:
var1="12345"
var2="a1234"

var3=`echo $var1 | grep [A-z]`
echo $var3
var3=`echo $var2 | grep [A-z]`
echo $var3

You will notice, if the variable(var1) has no alpha characters, then var3 will equal "".

if [ -z $var3 ] # if the string is empty
then
echo "the variable did not contain alpha characters"
fi

PS.
I this may not work well with characters like "?#$%^" etc.

bwkaz
10-10-2005, 06:44 PM
Yeesh! You don't want to use [A-z] -- this includes a bunch of non-letter characters.

If you want to test for letters, you would want to use [A-Za-z] instead, since that includes only letters. (Well, actually, that's wrong -- on EBCDIC character-set machines, it includes non-letters too. Come to think of it, the only completely safe way to check for an alphabetical character is [[:alpha:]].)

So, I'd try something like:

variable=whatevervalueyouwant

if [ echo "$variable" | grep -q [^[:alpha:]] ] ; then
echo "Variable contains non-letter characters."
else
echo "Variable contains only letters."
fi Note the -q option to grep, which tells it to not print the results, but just return the appropriate exit status. The ^ inside the character class means "match any character that isn't in this list".

Hediir
10-10-2005, 09:01 PM
Thanks. Got it.

Sepero
10-11-2005, 03:21 PM
bwkaz, showing me up. You bastard!

(Now I'll never be able to force him on Python :p)

bwkaz
10-11-2005, 07:04 PM
:p

(Er, Python? Do I know what you're referring to with that?)