26

I am a new student to bash scripting, and I am stumped on an assignment question. I was wondering if there is an easy way to determine whether a users' input is an integer or not. More specifically, if a user is prompted to input an integer, is there a quick check to validate?

6 Answers 6

42

One way is to check whether it contains non-number characters. You replace all digit characters with nothing and check for length -- if there's length there's non-digit characters.

if [[ -n ${input//[0-9]/} ]]; then
    echo "Contains letters!"
fi

Another approach is to check whether the variable, evaluated in arithmetic context, is equal to itself. This is bash-specific

if [[ $((foo)) != $foo ]]; then
    echo "Not just a number!"
fi
Sign up to request clarification or add additional context in comments.

1 Comment

If input is 5b for example, it will fail check.
21

This is kind of a kludge, it's using -eq for something other then what it was intended, but it checks for an integer, if it doesn't find an int it returns both an error which you can toss to /dev/null and a value of false.

read input
  if [[ $input ]] && [ $input -eq $input 2>/dev/null ]
  then
     echo "$input is an integer"
  else
     echo "$input is not an integer or not defined"
  fi

2 Comments

This assumes /dev/null exists
It also assumes the argument is not empty
17

You can test by using Regular expression

if ! [[ "$yournumber" =~ ^[0-9]+$ ]] ; 
 then exec >&2; echo "error: Not a number"; exit 1
fi

1 Comment

This is the most literal, and therefore easiest to remember.
3

I found this post http://www.unix.com/shell-programming-scripting/21668-how-check-whether-string-number-not.html that talks about this.

If your input does not need to check if there is a +/- on the number, then you can do:

expr $num + 1 2> /dev/null
if [ $? = 0 ]
then
    echo "Val was numeric"
else
    echo "Val was non-numeric"
fi

2 Comments

Simplest for integers. But doesn't support decimal fractions like 1.1, 1.2 etc
expr "$num" + 1 > /dev/null 2>&1 will avoid the value of $num + 1 being echoed to the stdout. Quotes around $num are there for safety. (in case $num has something with spaces in it like Foo Bar.)
1

Here is another way of doing it. It's probably a bit more elaborate than needed in most cases, but would handle decimals also. I had written the below code to get rounded number. It also checks for numeric input in the process.

    #--- getRound -- Gives number rounded to nearest integer -----------------------
    #    usage: getRound <inputNumber>
    #
    #    echos the rounded number
    #    Best to use it like:
    #      roundedNumber=`getRound $Number`
    #      check the return value ($?) and then process further
    #
    #    Return Value:
    #      2 - if <inputNumber> is not passed, or if more arguments are passed
    #      3 - if <inputNumber> is not a positive number
    #      0 - if <inputNumber> is successfully rounded
    #
    #    Limitation: Cannot be used for negative numbers
    #-------------------------------------------------------------------------------
    getRound (){
        if [ $# -ne 1 ]
        then
            exit 2
        fi

        #--- Check if input is a number
        Input=$1
        AB=`echo A${Input}B | tr -d [:digit:] | tr -d '.'`
        if [ "${AB}" != "AB" ] #--- Allow only '.' and digit
        then
            exit 3
        fi
        DOTorNone=`echo ${Input} | tr -d [:digit:]` #--- Allow only one '.'
        if [ "${DOTorNone}" != "" ] && [ "${DOTorNone}" != "." ]
        then
            exit 3
        fi

        echo $Input | awk '{print int($1+0.5)}' #--- Round to nearest integer
    }

    MyNumber=`getRound $1`
    if [ $? -ne 0 ]
    then
        echo "Empty or invalid input passed"
    else
        echo "Rounded input: $MyNumber"
    fi

Comments

0

This one works for me, handling empty input case.

if [ $input -eq $input 2>/dev/null -o $input -eq 0 2>/dev/null ]
then
   echo Integer
else
   echo Not an integer
fi

1 Comment

${input:-0} -eq ${input:1} should work as well, I suppose. (It’s about empty argument only)

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.