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?
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With