Script question
Polytropon
freebsd at edvax.de
Mon Jun 22 01:30:40 UTC 2015
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, ...
More information about the freebsd-questions
mailing list