Unix How-To: Checking Responses with ckyorn

By  

In last week's column, we looked at ckrange, a Solaris tool for validating numeric responses in scripts. A related command, ckyorn (for "check yes or no"), ensures that a user responds with some version of yes or no. With similar behavior to ckrange, ckyorn has the same advantages of simplifying your code so that you don't have to check whether a user has entered y, Y, Yes, yes, n, N, No, no or even YeS or nO.

To use ckyorn in a script, you need to first present your user wit the question that you want to ask. For example, you can echo a statement such as this:

echo "Please give your answer and don't be nervous"

Following this, you use the ckyorn command, assigning the user's response (once he or she hasn't answered in one of the acceptable forms) to a variable so that you can then continue with processing based on the user's response. Here's an example:

echo "Please give your answer and don't be nervous"
ans=`ckyorn`

When a user runs your script, he or she will see the following prompt:

     Yes or No [y,n,?,q]:

If a user types "?", an explanation (duh!) will provided. Of course, anyone having problems with "yes" and "no" will probably fall flat on his face when challenged with "affirmative".

        To respond in the affirmative, enter y, yes, Y, or YES. To respond in
        the negative, enter n, no, N, or NO.

Users also have the option of pressing q for "quit". In this case, however, it's "q" or it's nothing. Typing "Q", "quit" or "QUIT" won't cut it. Few users will object to this, I suspect.

As with ckrange, if the user types a response that isn't what the script wants, he or she will be prompted to try again -- for as long as they care to persist.

You can follow your ckyorn command with a case statement that takes different actions depending on whether the user responded positively, negatively or selected the quit response. Assuming you don't want to further interrogate your user if he or she ducks yur question by quitting, you can easily exit the script at that point as shown below.

#!/bin/bash

echo "Please give your answer and don't be nervous"
ans=`ckyorn`

case $ans in
    [Yy]*) echo "Very good.  We're glad you came around.";;
    [Nn]*) echo "So, what exactly are you objecting to?";;
    q)     exit;;
esac

As with ckrange, use of the ckyorn command reduces your scripting efforts significantly, ensures that you don't continue processing if your user presses "t" instead of "y" because he or she is gazing out the window, and leaves your script tidy and readable.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question
randomness