Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 22 Jun 2015 03:30:37 +0200
From:      Polytropon <freebsd@edvax.de>
To:        "Lt. Commander" <listmgr@antennex.com>
Cc:        freebsd-questions@freebsd.org
Subject:   Re: Script question
Message-ID:  <20150622033037.6cfd270d.freebsd@edvax.de>
In-Reply-To: <BAY404-EAS42803D52F7023B63CB38AFFCCA20@phx.gbl>
References:  <BAY182-W89C2924F4BDF0D2BD3810DF4BB0@phx.gbl> <BAY404-EAS148D4B304BB066F07E84004CCB90@phx.gbl> <20150615015516.b3ea7633.freebsd@edvax.de> <2609852.Pc7nSdcYla@desk8.phess.net> <BAY404-EAS3520468CFD04B6982A1487BCCA20@phx.gbl> <BAY404-EAS42803D52F7023B63CB38AFFCCA20@phx.gbl>

next in thread | previous in thread | raw e-mail | index | archive | help
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!"



-- 
Polytropon
Magdeburg, Germany
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20150622033037.6cfd270d.freebsd>