tags:

views:

715

answers:

2

Hi there

Im wrote a bash script that takes numbers for calculation via user input, the problem i have is if the user types a letter or a space by mistake the whole script fails and the user must start again.

There must be an easy way to check the input is numeric only that will ask for the input again if anything else is input accidentally.

any help will be much appreciated

thanks

Donaldo

+3  A: 

Use a while loop

number=""
while [[ ! $number =~ ^[0-9]+$ ]]; do
    echo Please enter your age
    read number
done
echo You are $number years old
Johannes Schaub - litb
Yes that works, thanks, but im re-using the same Variable so next time it comes round it has a value from the last entry.any ideas?
i don't quite understand what you mean. That's why we set it to an empty string before we enter the loop :)
Johannes Schaub - litb
The solution above still accepts input like '22aa', 'aa 22', or 'a23bb'. The regexp should include the start and the end of the string: while [[ ! ($number =~ ^[0-9]+$) ]]; do
fgm
You're right. fixed :)
Johannes Schaub - litb
Thanks litb while [[ ! ($number =~ ^[0-9]+$) ]]; dothats what i was aftermuch appreciateddanke
+3  A: 

And to avoid the heavy regex engine, use a simple glob:

if [[ $input = *[^0-9]* ]]; then
    echo "Error: '$input' is not a number." >&2
fi
lhunath
Oh, nice idea. i keep forgetting about [['s globbing facilities. i found it accepts "" though. "$input = "" || $input = *[^0-9]*" should fix it.
Johannes Schaub - litb