I'm writing a quick bash script and I only want to accept integers in between 0-9 as input. I've looked but haven't found much so apologies if the answer exists somewhere. I'll delete the post if another has the answer. Thank you
Asked
Active
Viewed 1,111 times
-1
-
1The first Google result for `bash read and check input` gives http://stackoverflow.com/q/848342/7010554. Does this help? – maij Nov 28 '16 at 21:19
1 Answers
3
#!/bin/bash
while [[ 1 ]] ; do
echo -n "Enter a number: "
read input
if [[ "$input" =~ ^[0-9]$ ]] ; then
break
fi
done
echo "Got $input"
Note that this option requires a bash that supports regular expressions. Also, it explicitly allows only a single integer, as you appeared to be requesting in your question.

eddiem
- 1,030
- 6
- 9
-
-
You don't need regular expressions to do this - glob patterns with `[[ $input == [0-9] ]]` would suffice. – Benjamin W. Nov 28 '16 at 22:07