nath
nath

Reputation: 212

How can I restrict bashs read command to only accept numeric values?

is there a way I can limit bashs read to only accept numeric input, so when anything else then a number is added, the user gets promted again?

read -r -p "please enter 2 numbers: " number

Upvotes: 0

Views: 2210

Answers (2)

feiiiiii
feiiiiii

Reputation: 1593

change all none numeric value to empty and check for length.

if [[ -n ${number//[0-9]/} ]]; then
    echo "please enter a numeric value!"
fi

Upvotes: 0

choroba
choroba

Reputation: 242323

Use a loop with a condition using a pattern:

#!/bin/bash
unset number
until [[ $number == +([0-9]) ]] ; do
    read -r -p "please enter a number: " number
done
echo $((number + 1))

You might need to be more precise (@(0|@([1-9])*([0-9]))) if you want to use the number directly, because e.g. 09 will cause an error, as it will be interpreted as octal because of the starting 0.

Upvotes: 3

Related Questions