Thursday, February 3, 2011

Unix Bash script - Check if integer or not


Please find below two UNIX bash scripts to test if the entered input is integer or not. Request all to suggest if any other alternatives to check this. Thanks in advance.
1) Script 1:

$ cat check-integer.sh
#!/bin/sh
#Check if input is integer or not

[ -z $1 ] && echo "No input, exiting .." && exit
[[ $1 = *[![:digit:]]* ]] && echo "Not Integer" || echo "Integer"

Executing/testing it:

$ ./check-integer.sh
No input, exiting ..

$ ./check-integer.sh 12
Integer

$ ./check-integer.sh 12.1
Not Integer

$ ./check-integer.sh testvar
Not Integer

2) Script 2:

#!/bin/sh
#Check if input is integer or not

[ -z $1 ] && echo "No input, exiting .." && exit
result=$(echo $1 | egrep ^[[:digit:]]+$)
if [ "$result" = "" ] ; then
echo "Not Integer"
else
echo "Integer"
fi

Executing/testing it:

$ ./check-integer.sh
No input, exiting ..

$ ./check-integer.sh 12
Integer

$ ./check-integer.sh 12.1
Not Integer

$ ./check-integer.sh testvar
Not Integer

$ ./check-integer.sh 12U
Not Integer

$ ./check-integer.sh U12
Not Integer

The if else in the second script can also be written using && and ||, something like:

[ "$result" = "" ] && echo "Not Integer" || echo "Integer"

Related posts:
- Use of $() as an alternative to backtick evaluation in bash
- UNIX Bash function to compare equality of multiple numbers

1 comment:

eric said...

#!/bin/bash

if [[ -n "$1" && "$(echo "$1" | tr -c -d 1234567890)" == "$1" ]];then
echo "INT"
else
echo "NOT INT"
fi

© Jadu Saikia www.UNIXCL.com