现在的位置: 首页 > 综合 > 正文

【BASH】如何得到用户输入的YES或NO

2014年01月05日 ⁄ 综合 ⁄ 共 2176字 ⁄ 字号 评论关闭

<!--
@page { margin: 0.79in }
P { margin-bottom: 0.08in }
-->

 

问题:

你需要从用户那里得到简单的yesno的输入,并且你期望做到用户界面的友好,做到能够区分大小写,并且提供用户点击Enter的默认选项。

 

解决方案

如果是简单的行为,可以使用下面这个函数。

#
cookbook filename: func_choose

#
Let the user make a choice about something and execute code based on

#
the answer

#
Called like: choose <default (y or n)> <prompt> <yes
action> <no action>

#
e.g. choose "y" /

#
"Do you want to play a game?" /

#
/usr/games/GlobalThermonucularWar /

#
'printf "%b" "See you later Professor Falkin."'
>&2

#
Returns: nothing

function
choose {

local
default="$1"

local
prompt="$2"

local
choice_yes="$3"

local
choice_no="$4"

local
answer

read
-p "$prompt" answer

[
-z "$answer" ] && answer="$default"

case
"$answer" in

[yY1]
) exec "$choice_yes"

#
error check

;;

[nN0]
) exec "$choice_no"

#
error check

;;

*
) printf "%b" "Unexpected answer '$answer'!"
>&2 ;;

esac

}
# end of function choose

 

如果是复杂的操作,可以使用下面的函数

#
cookbook filename: func_choice.1

#
Let the user make a choice about something and return a standardized

#
answer. How the default is handled and what happens next is up to

#
the if/then after the choice in main

#
Called like: choice <promtp>

#
e.g. choice "Do you want to play a game?"

$
Returns: global variable CHOICE

function
choice {

CHOICE=''

local
prompt="$*"

local
answer

read
-p "$prompt" answer

case
"$answer" in

[yY1]
) CHOICE='y';;

[nN0]
) CHOICE='n';;

*
) CHOICE="$answer";;

esac

}
# end of function choice

 

下面这段代码调用choice函数,提示用户确认时间。假设$THISPACKAGE已经设定,将显示时间并要求用户确认,如果用户选择yY,或者Enter,那么这个时间就被接受,如果用户输入一个新的时间,函数将循环并且要求用户确认。

#
cookbook filename: func_choice.2

until
[ "$CHOICE" = "y" ]; do

printf
"%b" "This package's date is $THISPACKAGE/n" >&2

choice
"Is that correct? [Y/,<New date>]: "

if
[ -z "$CHOICE" ]; then


CHOICE='y'

elif
[ "$CHOICE" != "y" ]; then

printf
"%b" "Overriding $THISPACKAGEwith ${CHOICE}/n"


THISPACKAGE=$CHOICE

fi

done

#
Build the package here

 

接下来,使用其他方法来解决这个问题。用户通过认真阅读提示和查看默认行为,可以简单的点击Enter,脚本将执行默认操作。

#
If the user types anything except a case insensitive 'n', they will

#
see the error log

choice
"Do you want to look at the error log file? [Y/n]: "

if
[ "$choice" != "n" ]; then

less
error.log

fi

#
If the user types anything except a case insensitive 'y', they will

#
not see the message log

choice
"Do you want to look at the message log file? [y/N]: "

if
[ "$choice" = "y" ]; then

less
message.log

fi

最后,如果用户没有输入,可以使用下面的方法解决

#
cookbook filename: func_choice.3

choice
"Enter your favorite color, if you have one: "

if
[ -n "$CHOICE" ]; then

printf
"%b" "You chose: $CHOICE"

else

printf
"%b" "You do not have a favorite color."

fi

 

 

 

抱歉!评论已关闭.