Register
It is currently Mon Oct 20, 2014 11:54 am

Verify input for a loop


All times are UTC - 6 hours


Post new topic Reply to topic  [ 3 posts ] 
Author Message
 PostPosted: Tue Jan 15, 2013 8:03 pm   

Joined: Tue Jan 15, 2013 7:50 pm
Posts: 2
I have created this test that works correctly if the user input is any number or letter but fails for any other input including a simple carriage return. Is there a better way to do this so it will work correctly for any input?
#!/bin/bash
#source pick Option START*********************************************
function pickOption()
{
OPTION="0"
while true;
do
if (( "$OPTION" < "1" )) || (( "$OPTION" > "3" )); then
echo "Select an option:"
echo "1. Do one "
echo "2. Do two "
echo "3. Do three "
read OPTION
else
break
fi
done
echo "option = " $OPTION
}
#source pick Option END*********************************************
##main##
pickOption
echo "option = " $OPTION


Top
 Profile  
 PostPosted: Fri Jan 18, 2013 7:43 pm   
Moderator
User avatar

Joined: Thu Oct 11, 2007 7:12 am
Posts: 229
Location: London - UK
In the style of what you already have;

Code:
#!/bin/bash
#source pick Option START*********************************************
function pickOption()
{
   OPTION="0"
   while true;
    do

      echo "Select an option:"
      echo "1. Do one "
      echo "2. Do two "
      echo "3. Do three "
      read OPTION

      # if OPTION empty or contains a non-digit then redo loop
      if [[ -z "$OPTION" || $OPTION =~ [^[:digit:]] ]]; then
         continue
      fi
      if (( "$OPTION" < "1" )) || (( "$OPTION" > "3" )); then
         continue
      fi
      break
   done
   echo "option = " $OPTION
}
#source pick Option END*********************************************
##main##
   pickOption
   echo "option = " $OPTION[/quote]


I wouldn't do it this way myself, I'd probably use the "case" command.

DW


Top
 Profile  
 PostPosted: Mon Jan 21, 2013 4:03 pm   

Joined: Tue Jan 15, 2013 7:50 pm
Posts: 2
Thank you DW. It works now. I didn't try the case command as I would have had the same verification problem.
Thanks again.
chas.........


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: Bing [Bot] and 4 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP