Problems with valid input

Hello all

I am having problems with a part of my script. Basically it asks for the user to enter a new id number for them. The catches are:-

  • It cannot already be existing (it will check a file)
  • It has to be four characters
  • It can only be numbers
  • It cannot call back into the function

The first three parts are simple but not calling itself is causing me problems. I was thinking about using nested while loops and heres what i have got so far. (It feels like i have lost the plot!!)

read input

while [ $input < 9999 ] 
do
           while [ 'echo $input | wc -c' < 4 ]
           do
                      while [ "$input" = 'grep $input file' ] 
                      do
                      read input
                      done
           read input
           done
read input
done

Any ideas would save me a lot of stress :cool:

hmm.. I dont think I would go with that many nested loops..

while true
do
  echo "Enter you number"
  read input
  if [ $input -lt 9999 -a ${#input} -eq 4 -a "$input" != `grep $input $file` ]
  then
    break
  else
    echo "number doesnt meet requirements... these are the requirements: blah"
  fi
done

This examples performs all your checks with one if statement... if it all checks out the loop breaks and $input is good to go for the rest of your script... if not the loop starts over. I didnt test this... so there might be some syntax errors on the test statements.

I am not sure what you mean with "It cannot call back into the function", but perhaps along the lines of this is what you are looking for:

while read input; do
  if (( input > 999 && input < 10000  )) &&\
     [[ $(grep -c "$input" file) -eq 0 ]]; then
    break
  fi
done

or

while read input; do
  case $input in
    [0-9][0-9][0-9][0-9])
      if [[ $(grep -c "$input" file) -eq 0 ]]; then
        break
      fi
  esac
done

or

while read input; do
  case $input in
    [0-9][0-9][0-9][0-9])
      grep "$input" file >/dev/null || break ;;
  esac
done