我想暂停shell脚本中的输入,并提示用户进行选择。标准的是、否或取消类型问题。如何在典型的bash提示符中完成此操作?
当前回答
检查此项
read -p "Continue? (y/n): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1
其他回答
read -p "Are you alright? (y/n) " RESP
if [ "$RESP" = "y" ]; then
echo "Glad to hear it"
else
echo "You need more bash programming"
fi
echo "Please enter some input: "
read input_variable
echo "You entered: $input_variable"
Bash为此选择了。以下是如何在脚本中使用它:
select result in Yes No Cancel
do
echo $result
done
这是它使用的样子:
$ bash examplescript.sh
1) Yes
2) No
3) Cancel
#? 1
Yes
#? 2
No
#? 3
Cancel
#?
可以在POSIX shell中处理区域设置感知的“是/否选项”;通过使用LC_MESSAGES语言环境类别的条目,witch提供了与输入匹配的现成RegEx模式,以及本地化Yes No的字符串。
#!/usr/bin/env sh
# Getting LC_MESSAGES values into variables
# shellcheck disable=SC2046 # Intended IFS splitting
IFS='
' set -- $(locale LC_MESSAGES)
yesexpr="$1"
noexpr="$2"
yesstr="$3"
nostr="$4"
messages_codeset="$5" # unused here, but kept as documentation
# Display Yes / No ? prompt into locale
echo "$yesstr / $nostr ?"
# Read answer
read -r yn
# Test answer
case "$yn" in
# match only work with the character class from the expression
${yesexpr##^}) echo "answer $yesstr" ;;
${noexpr##^}) echo "answer $nostr" ;;
esac
编辑:正如@Urhixidur在评论中提到的:
不幸的是,POSIX只指定了前两个(yeexpr和noexpr)。在Ubuntu 16上,yestr和nostr为空。
参见:https://www.ee.ryerson.ca/~courses/ele709/susv4/xrat/V_4_xbd_chap07.html#tag_21_07_03_06
LC_消息yestr和nostr语言环境关键字以及yesstr和nostr语言信息项以前用于匹配用户的肯定和否定响应。在POSIX.1-2008中,yeexpr、noexpr、yesexpr和noexpr扩展正则表达式已取代它们。应用程序应该使用通用的基于语言环境的消息传递工具来发出包含所需响应示例的提示消息。
或者使用Bash方式的区域设置:
#!/usr/bin/env bash
IFS=$'\n' read -r -d '' yesexpr noexpr _ < <(locale LC_MESSAGES)
printf -v yes_or_no_regex "(%s)|(%s)" "$yesexpr" "$noexpr"
printf -v prompt $"Please answer Yes (%s) or No (%s): " "$yesexpr" "$noexpr"
declare -- answer=;
until [[ "$answer" =~ $yes_or_no_regex ]]; do
read -rp "$prompt" answer
done
if [[ -n "${BASH_REMATCH[1]}" ]]; then
echo $"You answered: Yes"
else
echo $"No, was your answer."
fi
使用语言环境提供的regexp来匹配答案。
要翻译剩余的消息,请使用bash--dump po string scriptname输出po字符串以进行本地化:
#: scriptname:8
msgid "Please answer Yes (%s) or No (%s): "
msgstr ""
#: scriptname:17
msgid "You answered: Yes"
msgstr ""
#: scriptname:19
msgid "No, was your answer."
msgstr ""
更通用的是:
function menu(){
title="Question time"
prompt="Select:"
options=("Yes" "No" "Maybe")
echo "$title"
PS3="$prompt"
select opt in "${options[@]}" "Quit/Cancel"; do
case "$REPLY" in
1 ) echo "You picked $opt which is option $REPLY";;
2 ) echo "You picked $opt which is option $REPLY";;
3 ) echo "You picked $opt which is option $REPLY";;
$(( ${#options[@]}+1 )) ) clear; echo "Goodbye!"; exit;;
*) echo "Invalid option. Try another one.";continue;;
esac
done
return
}