-2

The following loop is looping when number is less than 1 or greater than 45 but it fails when the answer includes special characters such as [ % & * # ] etc

What can I change in the code in order to support this issue?

a=1
b=45


while [[ $answer -lt $a ]] || [[ $answer -gt $b ]]
do

echo -n "please answer"
read answer
done
  • 2
    Why would the answer have special characters? – Jesse_b Jul 20 '17 at 14:34
  • sorry - update it – yael Jul 20 '17 at 14:56
  • Actually, the only thing that code snippet produces is an error: please answer./numfail.sh: line 11: read: answer$': not a valid identifier – maulinglawns Jul 20 '17 at 14:56
1

You might rethink the whole concept. This is a simple snippet that will get you going.

#!/usr/bin/env bash

a=1
b=45


while read -p 'Please answer: ' answer
do
   re=$(printf '%s\n' "$answer" | tr -dc '[[:digit:]]')
   if ((re < a || re > b)); then
       read -p 'Please answer: ' $re
   else
       echo "Loop ended"
       exit 
   fi
 done
0

try this:

#!/bin/bash
#
a=1
b=45
#
while [[ $answer -lt $a || $answer -gt $b ]]; do

read -p "please answer: " answer
answer=$(echo "$answer" | tr -dc '[:alnum:]\n\r')

done

The answer=$(echo "$answer" | tr -dc '[:alnum:]\n\r') line will strip any special characters from the answer and reset the variable to the new value.

  • i prefer to continue the loop in case integer include characters as & or % etc – yael Jul 20 '17 at 14:42
  • see val0x00ff answers , he have nice solution – yael Jul 20 '17 at 14:51
  • @yael did some update but, not sure what your goal is. – Valentin Bajrami Jul 20 '17 at 15:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.