Force Input in User Defined Variable

In a line such as:

echo -n "How many days back would you like to check? "; read days

How can I ensure that the user has a.) entered a number between 1-30 (not 0 or 31+) and b.) has not just hit enter (ie set it to "") and if it's entered wrong, how do I start the if statement over?

I think I figured out my first question while typing. I have:
EDIT: I didnt figure it out at all :slight_smile:

if [ "$days" != [1-30] ]; then  #this doesnt work
echo "Please specify a number between 1 and 30."
echo -n "How many days back would you like to check? "; read days
else
...
fi

If they enter it wrong again, it errors. Is there a better way to do this?

It should be something like:

echo -n "How many days back would you like to check? "; read days

while [ "$days" -lt 1 -o "$days" -gt 30 ]
do
  echo "Please specify a number between 1 and 30."
  echo -n "How many days back would you like to check? "; read days
done

Regards

EDIT: Just reread your advice. Sounds good... I'll give it a try.

EDIT2: Works well Franklin. Thanks for the input... I guess I need to get out of the mindset of only using if as the test construct?

Earnstaf,
You already have a solution for your problem with the loop offered
by Franklin.
The loop assures you that only numbers between 1 and 30 are entered.

Also, you could test for the condition you actually want...
while [ ${days} -gt 1 ]; do

To assure the input isn't an empty string replace the while statement with:

while [ "$days" == "" ] || [ "$days" -lt 1 -o "$days" -gt 30 ]

BTW The use of the testoperator -o fails with:

while [ "$days" == "" ] -o [ "$days" -lt 1 -o "$days" -gt 30 ]

Does somebody have an explanation of that?
I'm home now and using Bash version 3.1.17, does this fail in ksh too?

Regards

while :
do
  printf "Enter day of month (1 - 30): "
  read day
  case $day in
    *[^0-9]* | "" | ???* )
       printf "Invalid number: \"%s\"\nPlease try again.\n\n" "$day"
       continue
       ;;
  esac
  if [ $day -gt 30 -o $day -lt 1 ]
  then
     printf "\nInvalid number: \"%s\"\nPlease try again.\n\n" "$day"
     continue
  fi
  break
done


Cfajohnson,
I have tried your solution and it does not work.
Could you please verify?

To fix the problem, instead of:

    *[^0-9]* | "" | ???* )

Use:

   .*[^0-9]* | "" | ???* )

What does "does not work" mean?
What happens?
What error messages do you get?
What input causes it to fail?

Try this line (i.e., replace '^' with '!'):

   *[!0-9]* | "" | ???* )

>>>What does "does not work" mean?
Means if a valid number between 1 and 30 is entered,
the solution will say it is invalid.

>>>What happens?
It continues in the loop.

>>>What error messages do you get?
Invalid number: "1"
Please try again.

>>>What input causes it to fail?
The normal, valid case of a number between 1 and 30.