Script question

Lt. Commander listmgr at antennex.com
Mon Jun 22 02:01:48 UTC 2015


From: owner-freebsd-questions at freebsd.org
[mailto:owner-freebsd-questions at freebsd.org] On Behalf Of Polytropon
Sent: Sunday, June 21, 2015 8:31 PM
To: Lt. Commander
Cc: freebsd-questions at freebsd.org
Subject: Re: Script question

On Sun, 21 Jun 2015 16:36:36 -0500, Lt. Commander wrote:
> Sheesh! Here's the script:
> #get_yes_no() {
>         while true
>         do
>                 echo -n "$1 (Y/N) ? " 
>                 read -t 30 a
>                 if [ $? != 0 ]; then
>                         a="No";
>                         return;
>                 fi
>                 case $a in
>                         [Yy]) a="Yes";
>                               return;;
>                         [Nn]) a="No";
>                               return;;
>                         *);;
>                 esac
>         done
> #}
> 
> get_yes_no "Do you want to continue......"
> 
> [ $a = 'No' ] && exit 1


I did a little re-formatting for readability, so you can spot the mistake
easier. The following code works as intended.

For the test cases: [ (or "test") uses -eq and ! -eq (or -ne) for numerical
values, but = and != for strings. See "man test"
for details.

Also note the removal of the ; after commands. Shell != C. :-)

You will see the following cases now (as expected):

	Do you want to continue (Y/N) ? y
	Continuing!

and

	Do you want to continue (Y/N) ? n

and the program exits with exit code 1. It accepts y, Y, n and N as valid
inputs, defaulting to the result "No" after 30 seconds.
Every other input causes the input loop to repeat.

Here's the code now:

#!/bin/sh

get_yes_no() {
	while true; do
		echo -n "$1 (Y/N) ? " 
		read -t 30 REPLY
		if [ ! $? -eq 0 ]; then
			ANSWER="No"
			return
		fi
		case "$REPLY" in
		[Yy])
			ANSWER="Yes"
			return
			;;
		[Nn])
			ANSWER="No"
			return
			;;
		*)
			;;
		esac
	done
}

get_yes_no "Do you want to continue"

[ $ANSWER = "No" ] && exit 1

echo "Continuing!"
-------------------------------------------------------
Bingo! You got it. Works fine.

Funny tho, I have used that little sh shell intro for years to lead into
various scripts. This is the first time it didn't work as I had it.

Oh, well... now it's fixed and that's all that counts.

Once again many thanks for the help!!

--Jason


--
Polytropon
Magdeburg, Germany
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...
_______________________________________________
freebsd-questions at freebsd.org mailing list
http://lists.freebsd.org/mailman/listinfo/freebsd-questions
To unsubscribe, send any mail to "freebsd-questions-unsubscribe at freebsd.org"


More information about the freebsd-questions mailing list