Home > Blockchain >  How do I make the shell program exit when the user enters an input that is not y or Y?
How do I make the shell program exit when the user enters an input that is not y or Y?

Time:11-17

I want to make the program exit out of the loop when the user types in a value that is not y or Y

#! /bin/sh
#initialise variable continue as "y"
continue="y"
while [ $continue = "y" -o "Y" ] # condition to continue the repetition
do
    echo "Please enter a station name to start search"
    read name

    result=`grep -w "^$name" STATIONS.TXT`
    if [ -z "$result" ]; then # the input station is not in the file
        echo "$name was not found in the file"
    else # the input station is in the file
        echo "$name was found in STATIONS.TXT"
    fi
    echo "Do you want to have another go? (enter y or Y to confirm, other to quit)"
    read input
    continue=$input`enter code here`
done
echo "End of the search program."

CodePudding user response:

Use while :; do for the while loop (or while true; do - they both return zero).

Then immediately after read input, use this to break the loop:

case $input in [Yy]);; *) break;; esac

This breaks the loop, and finishes the program, for anything other than a single y or Y.

CodePudding user response:

Your condition is quite close to how it should look, except that operator -o doesn't works on values but on entire expressions.

The correct notation would be:

while [ "$continue" = 'y' -o "$continue" = 'Y' ]

or a variant that is a little better defined in the standard (it works on greater variety of shell implementations):

while [ "$continue" = 'y' ] || [ "$continue" = 'Y' ]

or a little more universal way based on a regular expression which will allow to also match "yes" and "Yes":

while printf '%s' "$continue" | grep -q -x '[Yy]\(es\)\?'

(Notice that I've changed the style of quotation marks to a safer one.)

  • Related