Would like to check user input for letters within a loop


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Would like to check user input for letters within a loop
# 1  
Old 12-07-2018
Would like to check user input for letters within a loop

Hi All,

Code:
#!/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/

Code:
#!/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!

Last edited by Scrutinizer; 12-07-2018 at 03:16 PM.. Reason: code tags
# 2  
Old 12-07-2018
Hi you could try this using a unix pattern to test for non-digits
Code:
[[ $number == *[!0-9]* ]]

And this using a regular expression
Code:
[[ $number =~ [^0-9] ]]

--
this using a unix pattern to test for letters
Code:
[[ $number == *[[:alpha:]]* ]]

And this using a regular expression
Code:
[[ $number =~ [[:alpha:]] ]]

These 2 Users Gave Thanks to Scrutinizer For This Post:
# 3  
Old 12-10-2018
Hi,

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

Code:
#!/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!

Last edited by vgersh99; 12-10-2018 at 12:22 PM.. Reason: Code tags, please!
# 4  
Old 12-10-2018
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):

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

This User Gave Thanks to RudiC For This Post:
# 5  
Old 12-10-2018
a variable can contain different classes of characters.
universal method:
Code:
[ "${number//[0-9]}" ] && echo not a number

This User Gave Thanks to nezabudka For This Post:
# 6  
Old 12-14-2018
Thank you for the help! Working script as follows:

Code:
#!/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


Last edited by Corona688; 12-14-2018 at 02:57 PM..
# 7  
Old 12-14-2018
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 [code] and [/code] 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
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

How to check the user input to be valid using shell script?

How to check the user input to be valid using shell script? The valid input is in the format like as follows. 1. It can only have r,w,x or a hyphen and nothing else. 2. ensure the r, w, x are in the correct order. for example: rwxr-xr-x is a valid format. Thanks (5 Replies)
Discussion started by: hyeewang
5 Replies

2. Shell Programming and Scripting

How-To Check & Filter user input

Hi, On my Java webpage which invokes the shell script has two checkboxes viz ... apache and weblogic apache require one parameter i.e apache home from the user while Weblogic requires three or five params from the user vi.z weblogic_home or <jdk_home, config_home & pid>, username and... (4 Replies)
Discussion started by: mohtashims
4 Replies

3. Shell Programming and Scripting

Loop breaks on yes/no user input

I have a shell script, and its pretty much done, I decided to add a loop that ends or continues depending on user input. like "would you like to continue?" and if I hit y or yes it will run the loop again until I hit n or no and breaks out of the loop. To be hones I didn't think I needed to add... (2 Replies)
Discussion started by: Demon_Jester
2 Replies

4. Shell Programming and Scripting

Check user input

Hi, I need my script to check if the user enters 3 values if not 5 values to my script and alert if the input has any other number of values. for example: ./myscript.sh 22 56 3221 - > correct ./myscript.sh 22 56 3221 45 777 -> correct ./myscript.sh 22 56 3221 45 -> incorrect Please... (6 Replies)
Discussion started by: mohtashims
6 Replies

5. Homework & Coursework Questions

Function to Check if string input from user is alphabetic only

Good Evening. I'm new to C. Can you please help me. I'm creating an error checking function, user will input a string, this will check if the input is all alphabet or all letters only. If there is a digit or other special char, it will print Error then ask input from user again. Here's my... (1 Reply)
Discussion started by: eracav
1 Replies

6. Shell Programming and Scripting

matching user input to a text file loop?

until do read -p "Invalid cars. Try againa" cars1 done Ok i have the above code, im getting users input and if it doesnt match in the file the user has to try again untill its correct But when i run this it gives me an error saying ./Cars.bash: line 43: (2 Replies)
Discussion started by: gangsta
2 Replies

7. UNIX for Dummies Questions & Answers

Getting user input from inside a while loop?

I'm new to BASH and i'm trying to create a script which is simply put a large find and replace file. This is what I have so far N=0 while read LINE ; do N=$((N+1)) sed 's/'$2'/'$3'/g' $LINE > .temp echo "Changes to file $N = $LINE" echo 'The following changes... (5 Replies)
Discussion started by: Azumandious
5 Replies

8. UNIX for Dummies Questions & Answers

how to check the user input from terminal

Hello everybody!!! I am writing my own rm command in unix. I prompt the user to type if he wants to delete a file and then read what he typed. But how do i check what he typed? This is my program so far: echo 'Delete prog1.c (y/n)?' read yesOrNo if yesOrNo == 'y' then rm prog1.c... (6 Replies)
Discussion started by: mskart
6 Replies

9. Shell Programming and Scripting

Loop until user input is correct

Hello, i know how to retrieve a user input (read), and how to manage the different options (case statement). But... could anybody show me a script that, if the user option is incorrect, don't allow to continue the excution, i.e., if the value entered is not 1 or 2, the script shows a question. ... (2 Replies)
Discussion started by: aristegui
2 Replies

10. UNIX for Dummies Questions & Answers

read user input from within a wile loop that is being fed from below

hi! i need to do a ksh script that uses a wile loop that is fed form below while read line do some things done < myfile inside the while loop i need to read user input to ask the user what he wants to do, but "read" reads the file, and not the standard input while read line do ... (2 Replies)
Discussion started by: broli
2 Replies
Login or Register to Ask a Question