Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to determine if user input is an integer in bash?

Tags:

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?

like image 736
mrwienerdog Avatar asked Nov 09 '10 18:11

mrwienerdog


People also ask

How do you check if the input is integer or not?

Approach used below is as follows − Input the data. Apply isdigit() function that checks whether a given input is numeric character or not. This function takes single argument as an integer and also returns the value of type int. Print the resultant output.

Is integer in bash?

Bash lets you declare a variable to have the integer attribute, which guarantees that the variable always holds an integer value. It also permits arithmetic evaluation when assigning a value.


2 Answers

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 
like image 180
Daenyth Avatar answered Sep 22 '22 16:09

Daenyth


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 
like image 25
curriegrr Avatar answered Sep 21 '22 16:09

curriegrr