swa056
swa056

Reputation: 95

Read N chars or press enter to exit

I have the following function and I want when I press enter once to run the first case and then exit. Now I have to press enter 4 times to exit. Also, want when I press only one or two numbers and then enter to show the message "Number out of Range" immediately and not after two or three times per case.

function MakeSomething () {
    while true; do
        echo -en "Input : "
        read -N4 vn
        echo
        case $vn in
            "") if [ -z "$vn" ] ; then vn=3000 ; echo ${vn} ; exit ; fi ; break ;;
             *) [[ $vn =~ ^[0-9]+$ ]] || { echo -e '\nSorry input a number between 0011 and 2559\n' ; continue; } 
             if ((vn >= 0011 && vn <= 2559)); then echo ${vn} ; else echo -e '\nNumber out of Range, input a number between 0011 and 2559\n' ; fi ; MakeSomething ;break
        esac
    done
}

Upvotes: 0

Views: 153

Answers (1)

PatrickChen
PatrickChen

Reputation: 1430

First, let me answer your problem:

press the enter 4 times to exit.

This is because you're using read -N4, which means you read four characters from the input. So you need four Enter. My suggestion is to change to -a, read from input until Enter fix this.

I press only one or two numbers and then enter to show the message "Number out of Range" immediately and not after two or three times per case.

I think you shouldn't call the function inside the case clause because you already using a while loop. Should just let it continue.

Here is my code: // it works

#!/bin/sh

function MakeSomething () {
while true; do
echo -en "Input : "
read -a vn
echo
case $vn in
    "") if [ -z "$vn" ] ; then vn=3000 ; echo ${vn} ; exit ; fi ; break ;;
     *) [[ $vn =~ ^[0-9]+$ ]] || { echo -e '\nSorry input a number between 0011 and 2559\n' ; continue; }
# check input len
          if [ ${#vn} -ge 5 ] || [ ${#vn} -le 3 ]; then echo '\n need exactly four number'; continue; fi 
     if ((vn >= 0011 && vn <= 2559)); then echo ${vn} ; else echo -e '\nNumber out of Range, input a number between 0011 and 2559\n' ; fi
esac
done
}

MakeSomething

Upvotes: 1

Related Questions