Would like to check user input for letters within a loop

Hi All,

#!/bin/bash

#Just trying to check if letters are in the user input. Any tips?
# I have tried regexp and using 0-9 etc, i cannot get this to work either in just an if statement or while in a loop.

echo "Please pick a number"
read num
if [ -z $num ]; then
	echo "Please enter a number"
	read num
elif [[ $num != [[:digit:]] ]]; then
	echo "That is not a number, try again!"
	read num
# I have tried [0-9] etc and does not work.

elif	[[ $num = [[:digit:]] ]]; then
	echo $num
	echo "This is a number"
fi

# i understand this would need to be in a loop to continuously check until a number is chosen
# as of now it is always returning "That is not a number, try again!"
# I have an entire guessing working until i put anything that tries to verify if user input has letters.  If letters are present, i will be prompting for them to enter numbers within the loop.

THANKS!

--- Post updated at 07:02 PM ---

Got it to work but it only checks the first digit of the $number variable
Does anyone know how to have the have the script check if there are any letters throughout the $number variable/

#!/bin/bash
echo "Please pick number"
read number

if [ -z $number ]; then
echo "Please input a number"
read number

elif [[ ! $number == [0-9] ]]; then
echo "Not a number, Try again!"
read number

elif
[[ $number == [0-9]; then
echo $number
echo "That is a number!"
fi

# I can only check the first digit, how can i check the entire $number variable for any letters?

Thanks!

Hi you could try this using a unix pattern to test for non-digits

[[ $number == *[!0-9]* ]]

And this using a regular expression

[[ $number =~ [^0-9] ]]

--
this using a unix pattern to test for letters

[[ $number == *[[:alpha:]]* ]]

And this using a regular expression

[[ $number =~ [[:alpha:]] ]]
2 Likes

Hi,

Thank you for explaining that to me. The currently working script is as follows:

#!/bin/bash
win=no
echo "Please pick a number"
read number
while [ $win = no ]; do
if [ -z $number ]; then
echo "Please input a number"
win=no
read number
elif [[ "$number" == +([0-9]) ]]; then
echo "That is a number, Good Job!"
win=yes
elif [[ $number == +([[:alnum:]]) ]]; then
echo "That is not a number"
win=no
echo "Please input a number"
read number
fi
done

Thanks again for the help!

A few comments:

  • why the multiple read?
  • what are the + - signs in front of the regexes for?
  • good, consequent indentation helps people (and YOU!) understand your code faster and easier

As an idea for you a small code snippet that does the same as your code presented (may be enhanced by e.g. error checking and debugging code):

while [ ${win:-no} = "no" ]
  do    read -p"Pls enter number: " NMB
        if [[ "$NMB" =~ [^+-.[:digit:]] ]]
          then  echo "Not a number"
          else  echo "That is a number, Good Job!"
                win=yes
        fi
  done
1 Like

a variable can contain different classes of characters.
universal method:

[ "${number//[0-9]}" ] && echo not a number
1 Like

Thank you for the help! Working script as follows:

#!/bin/bash
# Set count to zero to track amount of guesses
# Set win=no for while loop condition
win=0
count=0
echo "What is your name?"
read name
echo "Hello, $name, welcome to the Grand Random Number Enumerator Guessing Game!"
echo "Please pick a number that will be the highest number in the game"
read number
while [[ $number != +([0-9]) ]]; do
	if [[ $number == ([[:alnum:]]) ]]; then
		echo "Please input a number"
		read number
	elif [[ $number == +([['!@#'$'%^&*()-=+']]) ]]; then
		echo "Please input a number"
		read number
	elif [[ $number == +([[:alpha:]]) ]]; then
		echo "Please put in a number"
		read number
	elif [ -z $number ]; then
		echo "Please enter a number"
		read number
	fi
done
secret=$(($RANDOM % $number + 1))
echo "You have chosen $number"
echo "I have picked a number between 1 and number"
echo "Try and guess my number!"
read guess
while [ $win = no ]; do
	if [ -z $guess ] || [[ $guess == +([[:alpha:]]) ]] || [[ $guess != +([[:digit:]]) ]] || [[ $guess == +(['!@#$%^*()_+]) ]]; then
		echo "Please enter a number"
		win=no
		read guess
	elif [ "$guess" -lt "$secret" ]; then
		echo "Higher, Please guess again"
		win=no
		count=$((count + 1))
		read guess
	elif [ "$guess" -gt "$secret" ]; then
		echo "Lower, please guess again"
		win=no
		count=$((count + 1))
		read guess
	elif [ "$guess" -eq "$secret" ]; then
		echo "WINNAH! YOU AHH WICKED SMAHT!"
		echo "It took you $count tries to guess my number"
		win=yes
	fi
done
echo "Would you like to play again?, <yes/no>"
read answer
checkagain=yes
while [ $checkagain = yes ]; do
	if [[ $answer == [Yy][Ee][Ss] ]]; then	
		exec /***/***/guessingame.sh
		checkagain=no
	elif [[ $answer == [Nn][Oo] ]]; then
		checkagain=no
		echo "YOU'RE FIRED!!!!"
		exit 0
	elif [[ $answer != ^[Yy][Ee][Ss]$ ]] || [[ $answer != ^[Nn][Oo]$ ]]; then
		checkagain=yes
		echo "Please input either "yes" or "no"
		read answer
	fi
done

To keep the forums high quality for all users, please take the time to format your posts correctly.

First of all, use Code Tags when you post any code or data samples so others can easily read your code. You can easily do this by highlighting your code and then clicking on the # in the editing menu. (You can also type code tags

```text
 and 
```

by hand.)

Second, avoid adding color or different fonts and font size to your posts. Selective use of color to highlight a single word or phrase can be useful at times, but using color, in general, makes the forums harder to read, especially bright colors like red.

Third, be careful when you cut-and-paste, edit any odd characters and make sure all links are working property.

Thank You.

The UNIX and Linux Forums

You can shorten it like this:

while
  printf "Please input a number: "
  read number
  [[ -z "$number" ]] || [[ $number == *[^0-9]* ]]
do
  echo "That is not a number"
done
echo "That is a number, Good Job!"

You can even stagger the conditions, via two nested while loops:

while
  while
    printf "Please input a number: "
    read number
    [[ -z "$number" ]]
  do
    :
  done
  [[ $number == *[^0-9]* ]]
do
  echo "That is not a number"
done
echo "That is a number, Good Job!"

How does it work?
The definition for a while loop is

while list
do list
done

where list is any (even multi-line, but not empty) shell code.
The last exit code in the while list determines if the loop should run or terminate.
The : is a no-op command that prevents an empty do list.

1 Like