我想暂停shell脚本中的输入,并提示用户进行选择。标准的是、否或取消类型问题。如何在典型的bash提示符中完成此操作?
echo "Please enter some input: "
read input_variable
echo "You entered: $input_variable"
inquire () {
echo -n "$1 [y/n]? "
read answer
finish="-1"
while [ "$finish" = '-1' ]
do
finish="1"
if [ "$answer" = '' ];
then
answer=""
else
case $answer in
y | Y | yes | YES ) answer="y";;
n | N | no | NO ) answer="n";;
*) finish="-1";
echo -n 'Invalid response -- please reenter:';
read answer;;
esac
fi
done
}
... other stuff
inquire "Install now?"
...
在shell提示符下获取用户输入的最简单和最广泛的方法是read命令。说明其用途的最佳方法是简单的演示:
while true; do
read -p "Do you wish to install this program? " yn
case $yn in
[Yy]* ) make install; break;;
[Nn]* ) exit;;
* ) echo "Please answer yes or no.";;
esac
done
Steven Huwig指出的另一种方法是Bash的select命令。下面是使用select的相同示例:
echo "Do you wish to install this program?"
select yn in "Yes" "No"; do
case $yn in
Yes ) make install; break;;
No ) exit;;
esac
done
使用select,您不需要清理输入–它会显示可用的选项,并键入与您的选择相对应的数字。它也会自动循环,所以如果它们提供了无效的输入,就不需要使用while true循环来重试。
此外,Léa Gris在她的回答中展示了一种使请求语言不可知的方法。调整我的第一个示例以更好地服务于多种语言可能如下所示:
set -- $(locale LC_MESSAGES)
yesexpr="$1"; noexpr="$2"; yesword="$3"; noword="$4"
while true; do
read -p "Install (${yesword} / ${noword})? " yn
if [[ "$yn" =~ $yesexpr ]]; then make install; exit; fi
if [[ "$yn" =~ $noexpr ]]; then exit; fi
echo "Answer ${yesword} / ${noword}."
done
显然,其他通信字符串在这里仍然没有翻译(Install,Answer),这需要在更完整的翻译中解决,但在许多情况下,即使是部分翻译也会很有用。
最后,请查看F.Hauri的优秀答案。
我建议你使用对话框。。。
Linux学徒:使用对话框改进Bash Shell脚本对话框命令允许在shell脚本中使用窗口框,以使其使用更具交互性。
它简单易用,还有一个名为gdialog的gnome版本,它采用了完全相同的参数,但在X上显示了GUI风格。
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
#?
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
您可以使用内置的read命令;使用-p选项向用户提示问题。
从BASH4开始,您现在可以使用-i建议答案:
read -e -p "Enter the path to the file: " -i "/usr/local/etc/" FILEPATH
echo $FILEPATH
(但请记住使用“readline”选项-e以允许使用箭头键进行行编辑)
如果你想要一个“是/否”的逻辑,你可以这样做:
read -e -p "
List the content of your home dir ? [Y/n] " YN
[[ $YN == "y" || $YN == "Y" || $YN == "" ]] && ls -la ~/
使用read命令:
echo Would you like to install? "(Y or N)"
read x
# now check if $x is "y"
if [ "$x" = "y" ]; then
# do something here!
fi
然后你需要的所有其他东西
这是我整理的东西:
#!/bin/sh
promptyn () {
while true; do
read -p "$1 " yn
case $yn in
[Yy]* ) return 0;;
[Nn]* ) return 1;;
* ) echo "Please answer yes or no.";;
esac
done
}
if promptyn "is the sky blue?"; then
echo "yes"
else
echo "no"
fi
我是一个初学者,所以要谨慎对待,但它似乎奏效了。
yn() {
if [[ 'y' == `read -s -n 1 -p "[y/n]: " Y; echo $Y` ]];
then eval $1;
else eval $2;
fi }
yn 'echo yes' 'echo no'
yn 'echo absent no function works too!'
此解决方案读取单个字符,并在yes响应时调用函数。
read -p "Are you sure? (y/n) " -n 1
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
do_something
fi
多选版本:
ask () { # $1=question $2=options
# set REPLY
# options: x=..|y=..
while $(true); do
printf '%s [%s] ' "$1" "$2"
stty cbreak
REPLY=$(dd if=/dev/tty bs=1 count=1 2> /dev/null)
stty -cbreak
test "$REPLY" != "$(printf '\n')" && printf '\n'
(
IFS='|'
for o in $2; do
if [ "$REPLY" = "${o%%=*}" ]; then
printf '\n'
break
fi
done
) | grep ^ > /dev/null && return
done
}
例子:
$ ask 'continue?' 'y=yes|n=no|m=maybe'
continue? [y=yes|n=no|m=maybe] g
continue? [y=yes|n=no|m=maybe] k
continue? [y=yes|n=no|m=maybe] y
$
它会将REPLY设置为y(在脚本中)。
要获得像inputbox这样的漂亮ncurses,请使用如下命令对话框:
#!/bin/bash
if (dialog --title "Message" --yesno "Want to do something risky?" 6 25)
# message box will have the size 25x6 characters
then
echo "Let's do something risky"
# do something risky
else
echo "Let's stay boring"
fi
默认情况下,对话框包至少在SUSE Linux上安装。看起来像:
在我的情况下,我需要从下载的脚本中读取。,
curl -Ss https://example.com/installer.sh | sh
在这种情况下,read-ryn</dev/tty行允许它读取输入。
printf "These files will be uploaded. Is this ok? (y/N) "
read -r yn </dev/tty
if [ "$yn" = "y" ]; then
# Yes
else
# No
fi
受到@Mark和@Myrdin的回答的启发,我创建了一个通用提示的函数
uniprompt(){
while true; do
echo -e "$1\c"
read opt
array=($2)
case "${array[@]}" in *"$opt"*) eval "$3=$opt";return 0;; esac
echo -e "$opt is not a correct value\n"
done
}
这样使用:
unipromtp "Select an option: (a)-Do one (x)->Do two (f)->Do three : " "a x f" selection
echo "$selection"
一个通用问题至少有五个答案。
取决于
posix兼容:可以在具有通用shell环境的较差系统上工作特定于bash:使用所谓的bashms
如果你想
简单的“在线”问题/答案(通用解决方案)漂亮的格式化界面,如ncurses或更多使用libgtk或libqt的图形界面。。。使用强大的读取线历史记录功能
1.POSIX通用解决方案
您可以使用read命令,后跟if。。。然后其他:
printf 'Is this a good question (y/n)? '
read answer
#如果echo“$answer”| grep-iq“^y”;然后
if [ "$answer" != "${answer#[Yy]}" ] ;then # this grammar (the #[] operator) means that the variable $answer where any Y or y in 1st position will be dropped if they exist.
echo Yes
else
echo No
fi
(感谢Adam Katz的评论:将上面的测试替换为更便携且避免使用分叉的测试:)
POSIX,但一键功能
但如果你不想让用户点击Return,你可以这样写:
(编辑:正如@JonathanLeffler正确地建议的那样,保存stty的配置可能比简单地强迫他们保持理智要好。)
printf 'Is this a good question (y/n)? '
old_stty_cfg=$(stty -g)
stty raw -echo ; answer=$(head -c 1) ; stty $old_stty_cfg # Careful playing with stty
if [ "$answer" != "${answer#[Yy]}" ];then
echo Yes
else
echo No
fi
注意:这是在sh、bash、ksh、dash和busybox下测试的!
相同,但明确等待y或n:
#/bin/sh
printf 'Is this a good question (y/n)? '
old_stty_cfg=$(stty -g)
stty raw -echo
answer=$( while ! head -c 1 | grep -i '[ny]' ;do true ;done )
stty $old_stty_cfg
if [ "$answer" != "${answer#[Yy]}" ];then
echo Yes
else
echo No
fi
使用专用工具
有许多工具是使用libncurses、libgtk、libqt或其他图形库构建的。例如,使用whibtail:
if whiptail --yesno "Is this a good question" 20 60 ;then
echo Yes
else
echo No
fi
根据您的系统,您可能需要用另一个类似的工具替换whibtail:
dialog --yesno "Is this a good question" 20 60 && echo Yes
gdialog --yesno "Is this a good question" 20 60 && echo Yes
kdialog --yesno "Is this a good question" 20 60 && echo Yes
其中20是以行数表示的对话框的高度,60是对话框的宽度。这些工具都具有几乎相同的语法。
DIALOG=whiptail
if [ -x /usr/bin/gdialog ] ;then DIALOG=gdialog ; fi
if [ -x /usr/bin/xdialog ] ;then DIALOG=xdialog ; fi
...
$DIALOG --yesno ...
2.具体的解决方案
基本在线方法
read -p "Is this a good question (y/n)? " answer
case ${answer:0:1} in
y|Y )
echo Yes
;;
* )
echo No
;;
esac
我更喜欢使用case,所以如果需要,我甚至可以测试yes | ja | si | oui。。。
符合单键功能
在bash下,我们可以为read命令指定预期输入的长度:
read -n 1 -p "Is this a good question (y/n)? " answer
在bash下,read命令接受超时参数,这可能很有用。
read -t 3 -n 1 -p "Is this a good question (Y/n)? " answer
[ -z "$answer" ] && answer="Yes" # if 'yes' have to be default choice
带倒计时的超时:
i=6 ;while ((i-->1)) &&
! read -sn 1 -t 1 -p $'\rIs this a good question (Y/n)? '$i$'..\e[3D' answer;do
:;done ;[[ $answer == [nN] ]] && answer=No || answer=Yes ;echo "$answer "
3.专用工具的一些技巧
除了简单的“是-否”目的之外,更复杂的对话框:
dialog --menu "Is this a good question" 20 60 12 y Yes n No m Maybe
进度条:
dialog --gauge "Filling the tank" 20 60 0 < <(
for i in {1..100};do
printf "XXX\n%d\n%(%a %b %T)T progress: %d\nXXX\n" $i -1 $i
sleep .033
done
)
小演示:
#!/bin/sh
while true ;do
[ -x "$(which ${DIALOG%% *})" ] || DIALOG=dialog
DIALOG=$($DIALOG --menu "Which tool for next run?" 20 60 12 2>&1 \
whiptail "dialog boxes from shell scripts" >/dev/tty \
dialog "dialog boxes from shell with ncurses" \
gdialog "dialog boxes from shell with Gtk" \
kdialog "dialog boxes from shell with Kde" ) || break
clear;echo "Choosed: $DIALOG."
for i in `seq 1 100`;do
date +"`printf "XXX\n%d\n%%a %%b %%T progress: %d\nXXX\n" $i $i`"
sleep .0125
done | $DIALOG --gauge "Filling the tank" 20 60 0
$DIALOG --infobox "This is a simple info box\n\nNo action required" 20 60
sleep 3
if $DIALOG --yesno "Do you like this demo?" 20 60 ;then
AnsYesNo=Yes; else AnsYesNo=No; fi
AnsInput=$($DIALOG --inputbox "A text:" 20 60 "Text here..." 2>&1 >/dev/tty)
AnsPass=$($DIALOG --passwordbox "A secret:" 20 60 "First..." 2>&1 >/dev/tty)
$DIALOG --textbox /etc/motd 20 60
AnsCkLst=$($DIALOG --checklist "Check some..." 20 60 12 \
Correct "This demo is useful" off \
Fun "This demo is nice" off \
Strong "This demo is complex" on 2>&1 >/dev/tty)
AnsRadio=$($DIALOG --radiolist "I will:" 20 60 12 \
" -1" "Downgrade this answer" off \
" 0" "Not do anything" on \
" +1" "Upgrade this anser" off 2>&1 >/dev/tty)
out="Your answers:\nLike: $AnsYesNo\nInput: $AnsInput\nSecret: $AnsPass"
$DIALOG --msgbox "$out\nAttribs: $AnsCkLst\nNote: $AnsRadio" 20 60
done
更多样品?查看使用whiptail选择USB设备和USB可移动存储选择器:USBKeyChooser
5.使用readline的历史记录
例子:
#!/bin/bash
set -i
HISTFILE=~/.myscript.history
history -c
history -r
myread() {
read -e -p '> ' $1
history -s ${!1}
}
trap 'history -a;exit' 0 1 2 3 6
while myread line;do
case ${line%% *} in
exit ) break ;;
* ) echo "Doing something with '$line'" ;;
esac
done
这将在$HOME目录中创建一个文件.myscript.history,您可以使用readline的历史记录命令,如Up、Down、Ctrl+r等。
一种简单的方法是使用xargs-p或gnu-parallel-interactive。
我更喜欢xargs的行为,因为它像其他交互式unix命令一样,在提示符后立即执行每个命令,而不是收集yes以在最后运行。(在完成所需任务后,可以按Ctrl-C键。)
例如。,
echo *.xml | xargs -p -n 1 -J {} mv {} backup/
read -e -p "Enter your choice: " choice
-e选项允许用户使用箭头键编辑输入。
如果要使用建议作为输入:
read -e -i "yes" -p "Enter your choice: " choice
-i选项打印提示性输入。
作为单行命令的朋友,我使用了以下命令:
while [ -z $prompt ]; do read -p "Continue (y/n)?" choice;case "$choice" in y|Y ) prompt=true; break;; n|N ) exit 0;; esac; done; prompt=;
以长格式编写,其工作原理如下:
while [ -z $prompt ];
do read -p "Continue (y/n)?" choice;
case "$choice" in
y|Y ) prompt=true; break;;
n|N ) exit 0;;
esac;
done;
prompt=;
更通用的是:
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
}
您需要:
Bash内置命令(即便携式)检查TTY默认答案超时彩色问题
一小条
do_xxxx=y # In batch mode => Default is Yes
[[ -t 0 ]] && # If TTY => Prompt the question
read -n 1 -p $'\e[1;32m
Do xxxx? (Y/n)\e[0m ' do_xxxx # Store the answer in $do_xxxx
if [[ $do_xxxx =~ ^(y|Y|)$ ]] # Do if 'y' or 'Y' or empty
then
xxxx
fi
解释
[[-t 0]]&&read…=>如果TTY,调用命令读取read-n 1=>等待一个字符$'\e[1;32m…\e[0m'=>绿色打印(绿色很好,因为在白色/黑色背景上都可以阅读)[[$do_xxxx=~^(y|y|)$]]=>bash正则表达式
超时=>默认答案为否
do_xxxx=y
[[ -t 0 ]] && { # Timeout 5 seconds (read -t 5)
read -t 5 -n 1 -p $'\e[1;32m
Do xxxx? (Y/n)\e[0m ' do_xxxx || # read 'fails' on timeout
do_xxxx=n ; } # Timeout => answer No
if [[ $do_xxxx =~ ^(y|Y|)$ ]]
then
xxxx
fi
用最少的行数实现这一点的最简单方法如下:
read -p "<Your Friendly Message here> : y/n/cancel" CONDITION;
if [ "$CONDITION" == "y" ]; then
# do something here!
fi
if只是一个例子:如何处理这个变量取决于您。
在这种情况下,我已经多次使用case语句,使用case语句是一种很好的方法。可以实现while循环,该循环模拟case块,利用布尔条件,以便更好地控制程序,并满足许多其他要求。在满足所有条件后,可以使用中断,将控制权传递回程序的主要部分。此外,为了满足其他条件,当然可以在控制结构中添加条件语句:case语句和可能的while循环。
使用案例陈述来满足您的请求的示例
#! /bin/sh
# For potential users of BSD, or other systems who do not
# have a bash binary located in /bin the script will be directed to
# a bourne-shell, e.g. /bin/sh
# NOTE: It would seem best for handling user entry errors or
# exceptions, to put the decision required by the input
# of the prompt in a case statement (case control structure),
echo Would you like us to perform the option: "(Y|N)"
read inPut
case $inPut in
# echoing a command encapsulated by
# backticks (``) executes the command
"Y") echo `Do something crazy`
;;
# depending on the scenario, execute the other option
# or leave as default
"N") echo `execute another option`
;;
esac
exit
我注意到,对于这样简单的用户输入,没有人发布显示多行回声菜单的答案,所以我的做法如下:
#!/bin/bash
function ask_user() {
echo -e "
#~~~~~~~~~~~~#
| 1.) Yes |
| 2.) No |
| 3.) Quit |
#~~~~~~~~~~~~#\n"
read -e -p "Select 1: " choice
if [ "$choice" == "1" ]; then
do_something
elif [ "$choice" == "2" ]; then
do_something_else
elif [ "$choice" == "3" ]; then
clear && exit 0
else
echo "Please select 1, 2, or 3." && sleep 3
clear && ask_user
fi
}
ask_user
发布这种方法是希望有人发现它有用且省时。
是/否/取消
作用
#!/usr/bin/env bash
@confirm() {
local message="$*"
local result=''
echo -n "> $message (Yes/No/Cancel) " >&2
while [ -z "$result" ] ; do
read -s -n 1 choice
case "$choice" in
y|Y ) result='Y' ;;
n|N ) result='N' ;;
c|C ) result='C' ;;
esac
done
echo $result
}
用法
case $(@confirm 'Confirm?') in
Y ) echo "Yes" ;;
N ) echo "No" ;;
C ) echo "Cancel" ;;
esac
使用干净的用户输入进行确认
作用
#!/usr/bin/env bash
@confirm() {
local message="$*"
local result=3
echo -n "> $message (y/n) " >&2
while [[ $result -gt 1 ]] ; do
read -s -n 1 choice
case "$choice" in
y|Y ) result=0 ;;
n|N ) result=1 ;;
esac
done
return $result
}
用法
if @confirm 'Confirm?' ; then
echo "Yes"
else
echo "No"
fi
针对其他人:
您不需要在BASH4中指定大小写,只需使用',,'使var小写即可。此外,我强烈不喜欢将代码放在读取块内,获取结果并在读取块IMO外处理它。还包括一个“q”表示退出IMO。最后,为什么键入“yes”只需使用-n1并按y。
示例:用户可以按y/n和q退出。
ans=''
while true; do
read -p "So is MikeQ the greatest or what (y/n/q) ?" -n1 ans
case ${ans,,} in
y|n|q) break;;
*) echo "Answer y for yes / n for no or q for quit.";;
esac
done
echo -e "\nAnswer = $ans"
if [[ "${ans,,}" == "q" ]] ; then
echo "OK Quitting, we will assume that he is"
exit 0
fi
if [[ "${ans,,}" == "y" ]] ; then
echo "MikeQ is the greatest!!"
else
echo "No? MikeQ is not the greatest?"
fi
仅单个按键
这里有一个更长但可重复使用的模块化方法:
返回0=yes和1=no无需按enter键-仅需一个字符可以按enter键接受默认选择可以禁用默认选项以强制选择适用于zsh和bash。
按enter键时默认为“否”
请注意,N是大写的。此处按enter键,接受默认值:
$ confirm "Show dangerous command" && echo "rm *"
Show dangerous command [y/N]?
还要注意,[y/N]?已自动追加。默认的“no”被接受,因此不会有任何回音。
重新提示,直到给出有效响应:
$ confirm "Show dangerous command" && echo "rm *"
Show dangerous command [y/N]? X
Show dangerous command [y/N]? y
rm *
按回车键时默认为“是”
请注意,Y是大写的:
$ confirm_yes "Show dangerous command" && echo "rm *"
Show dangerous command [Y/n]?
rm *
上面,我刚刚按了回车键,所以命令运行了。
输入时无默认值-需要y或n
$ get_yes_keypress "Here you cannot press enter. Do you like this [y/n]? "
Here you cannot press enter. Do you like this [y/n]? k
Here you cannot press enter. Do you like this [y/n]?
Here you cannot press enter. Do you like this [y/n]? n
$ echo $?
1
这里,返回了1或false。请注意,使用此较低级别的函数,您需要提供自己的[y/n]?促使
Code
# Read a single char from /dev/tty, prompting with "$*"
# Note: pressing enter will return a null string. Perhaps a version terminated with X and then remove it in caller?
# See https://unix.stackexchange.com/a/367880/143394 for dealing with multi-byte, etc.
function get_keypress {
local REPLY IFS=
>/dev/tty printf '%s' "$*"
[[ $ZSH_VERSION ]] && read -rk1 # Use -u0 to read from STDIN
# See https://unix.stackexchange.com/q/383197/143394 regarding '\n' -> ''
[[ $BASH_VERSION ]] && </dev/tty read -rn1
printf '%s' "$REPLY"
}
# Get a y/n from the user, return yes=0, no=1 enter=$2
# Prompt using $1.
# If set, return $2 on pressing enter, useful for cancel or defualting
function get_yes_keypress {
local prompt="${1:-Are you sure [y/n]? }"
local enter_return=$2
local REPLY
# [[ ! $prompt ]] && prompt="[y/n]? "
while REPLY=$(get_keypress "$prompt"); do
[[ $REPLY ]] && printf '\n' # $REPLY blank if user presses enter
case "$REPLY" in
Y|y) return 0;;
N|n) return 1;;
'') [[ $enter_return ]] && return "$enter_return"
esac
done
}
# Credit: http://unix.stackexchange.com/a/14444/143394
# Prompt to confirm, defaulting to NO on <enter>
# Usage: confirm "Dangerous. Are you sure?" && rm *
function confirm {
local prompt="${*:-Are you sure} [y/N]? "
get_yes_keypress "$prompt" 1
}
# Prompt to confirm, defaulting to YES on <enter>
function confirm_yes {
local prompt="${*:-Are you sure} [Y/n]? "
get_yes_keypress "$prompt" 0
}
您可以在读取时使用默认REPLY,将其转换为小写,并使用表达式与一组变量进行比较。该脚本还支持ja/si/oui
read -rp "Do you want a demo? [y/n/c] "
[[ ${REPLY,,} =~ ^(c|cancel)$ ]] && { echo "Selected Cancel"; exit 1; }
if [[ ${REPLY,,} =~ ^(y|yes|j|ja|s|si|o|oui)$ ]]; then
echo "Positive"
fi
可以在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 ""
这是我在脚本/函数中通常需要的:
如果按ENTER键,默认答案为“是”也接受z(如果你在QWERTZ布局上搞混了)接受其他语言(“ja”、“Oui”、…)如果您在函数内部,请处理正确的出口
while true; do
read -p "Continue [Y/n]? " -n 1 -r -e yn
case "${yn:-Y}" in
[YyZzOoJj]* ) echo; break ;;
[Nn]* ) [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1 ;; # handle exits from shell or function but don't exit interactive shell
* ) echo "Please answer yes or no.";;
esac
done
echo "and off we go!"
绝对最简单的解决方案是这一行,没有巧妙的技巧:
read -p "press enter ..." y
它让人想起了经典的DOS点击任意键继续,除了它等待Enter键,而不仅仅是任何键。
的确,这并没有为您提供“是”“否”“取消”的三个选项,但在您接受control-C作为“否”的情况下,这很有用。在简单脚本中取消,例如:
#!/bin/sh
echo Backup this project
read -p "press enter ..." y
rsync -tavz . /media/hard_to_remember_path/backup/projects/yourproject/
因为您不需要记住难看的命令和路径,但也不需要记住运行速度过快的脚本,而不需要在您决定它不是您想要运行的脚本之前停止。
检查此项
read -p "Continue? (y/n): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1
我为回答是/否问题编写了一个小脚本:https://github.com/optimistiCli/getans
例子:
#!/bin/bash
if ! getans.sh 'Shall we proceed?' y ; then
echo "User said “NO”"
exit 1
fi
echo "User said “YES”"
# do something usefull
exit 0
直接链接:https://github.com/optimistiCli/getans/raw/main/getans.sh
一个衬垫:
read -p "Continue? [Enter] → Yes, [Ctrl]+[C] → No."
这假设“否”和“取消”具有相同的结果,因此没有理由区别对待它们。
使用PyInquirer的一行python替代方案
python3 -c 'import PyInquirer; print(PyInquirer.prompt([{"type":"confirm", "message":"Do you want to continue?", "name":"r"}]).get("r"))'
它支持yes/no/cancel(intr,CTRL+C)。
您可以编写一个函数来测试:
confirm() {
local ans IFS=;
while read -rp "$1" -n1 ans;
do printf '\n';
case $ans in [Yy]) return 0;;
[Nn]) return 1;;
esac;
done;
}; ## Usage: if confirm "Are you sure? "; then ...
if confirm "Does everything look ok...reboot now? [Y/n]"; then
echo "rebooting..."
sleep 5
reboot
fi
这个问题有很多很好的答案,但从我看来,没有一个是我的理想,那就是:
简单一点,只需要几行外壳使用单个y/n键(无需按enter键)如果只按回车键,则默认为yes也可以使用大写的Y/N
这是我的版本,它具有这些财产:
read -n1 -p "Continue? (Y/n) " confirm
if ! echo $confirm | grep '^[Yy]\?$'; then
exit 1
fi
如果要在两个分支上运行代码,可以修改该条件,使其仅在“yes”上运行(只需删除if语句中的!)或添加else。
推荐文章
- 在Unix中,我可以在一个目录中运行'make'而不首先cd'到该目录吗?
- Github权限被拒绝:ssh添加代理没有身份
- 在bash中使用正则表达式进行搜索和替换
- 如何从命令行重置Jenkins安全设置?
- 如何查看Linux共享库正在导出的函数列表?
- 在Docker Alpine容器中启动一个shell
- 如何在Python中实现常见的bash习语?
- 如何通过docker运行传递参数到Shell脚本
- Bash“if [false];”返回true而不是false——为什么?
- 在shell脚本中使用$()而不是反引号的好处是什么?
- 快速unix命令显示文件中间的特定行?
- fork(), vfork(), exec()和clone()的区别
- 如何从查找“类型d”中排除此/ current / dot文件夹
- 检查bash变量是否等于0
- 在tmux中保持窗口名称固定