我想在shell脚本中暂停输入,并提示用户进行选择。标准的“是,否或取消”类型问题。如何在典型的bash提示符中完成此操作?
答案 0 :(得分:1421)
在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
循环重试。
另外,请查看F. Hauri的excellent answer。
答案 1 :(得分:448)
取决于
如果你想要
您可以使用read
命令,然后使用if ... then ... else
:
echo -n "Is this a good question (y/n)? "
read answer
# if echo "$answer" | grep -iq "^y" ;then
if [ "$answer" != "${answer#[Yy]}" ] ;then
echo Yes
else
echo No
fi
(感谢Adam Katz's comment:将上面的测试替换为更便携且避免使用一个分叉的测试:)
但如果您不希望用户必须点击 Return ,您可以写:
(编辑:正如@JonathanLeffler正确建议的那样,保存 stty的配置可能比仅仅强迫他们理智更好。)
echo -n "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 echo "$answer" | grep -iq "^y" ;then
echo Yes
else
echo No
fi
注意:这是在sh,bash,ksh,dash和busybox下进行测试的!
相同,但明确等待 y 或 n :
#/bin/sh
echo -n "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 echo "$answer" | grep -iq "^y" ;then
echo Yes
else
echo No
fi
有许多工具是使用libncurses
,libgtk
,libqt
或其他图形库构建的。例如,使用whiptail
:
if whiptail --yesno "Is this a good question" 20 60 ;then
echo Yes
else
echo No
fi
根据您的系统,您可能需要使用其他类似工具替换whiptail
:
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 ...
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
命令接受 timeout 参数,这可能很有用。
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
更复杂的对话框,超出简单的 yes - no
目的:
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" ) || exit
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
更多样本?请查看Using whiptail for choosing USB device和USB removable storage selector: USBKeyChooser
示例:
#!/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
这将在.myscript.history
目录中创建一个文件$HOME
,而不是使用readline的历史命令,例如 Up , Down ,< kbd> Ctrl + r 等。
答案 2 :(得分:340)
echo "Please enter some input: "
read input_variable
echo "You entered: $input_variable"
答案 3 :(得分:151)
您可以使用内置的read命令;使用-p
选项提示用户提问。
自BASH4起,您现在可以使用-i
来建议答案,因此用户只需按return
即可输入:
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 ~/
答案 4 :(得分:102)
为此目的,Bash有select。
select result in Yes No Cancel
do
echo $result
done
答案 5 :(得分:54)
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
答案 6 :(得分:32)
这是我放在一起的东西:
#!/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
我是初学者,所以请稍等一下,但这似乎有效。
答案 7 :(得分:28)
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?"
...
答案 8 :(得分:25)
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 ...
=&gt;如果TTY read
read -n 1
=&gt;等一个角色$'\e[1;32m ... \e[0m '
=&gt;以绿色打印[[ $do_xxxx =~ ^(y|Y|)$ ]]
=&gt; bash regex 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
答案 9 :(得分:21)
使用最少行数实现此目的的最简单方法如下:
read -p "<Your Friendly Message here> : y/n/cancel" CONDITION;
if [ "$CONDITION" == "y" ]; then
# do something here!
fi
if
只是一个例子:由你来决定如何处理这个变量。
答案 10 :(得分:17)
使用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
然后你需要的所有其他东西
答案 11 :(得分:17)
此解决方案读取单个字符并在yes响应上调用函数。
read -p "Are you sure? (y/n) " -n 1
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
do_something
fi
答案 12 :(得分:12)
read -e -p "Enter your choice: " choice
-e
选项允许用户使用箭头键编辑输入。
如果您想使用建议作为输入:
read -e -i "yes" -p "Enter your choice: " choice
-i
选项会打印一个暗示性输入。
答案 13 :(得分:10)
很抱歉在这么老的帖子上发帖。几周前我遇到了类似的问题,在我的情况下,我需要一个解决方案,它也可以在一个在线安装程序脚本中工作,例如:curl -Ss https://raw.github.com/_____/installer.sh | bash
使用read yesno < /dev/tty
对我来说很好用:
echo -n "These files will be uploaded. Is this ok? (y/n) "
read yesno < /dev/tty
if [ "x$yesno" = "xy" ];then
# Yes
else
# No
fi
希望这有助于某人。
答案 14 :(得分:8)
要获得类似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上。
答案 15 :(得分:6)
您可以在REPLY
上使用默认的read
,将其转换为小写并与带有表达式的一组变量进行比较。
该脚本还支持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
答案 16 :(得分:6)
这是一个更长的但可重用的模块化方法:
0
=是和1
=否zsh
和bash
。请注意,N
是大写的。按下回车键,接受默认值:
$ confirm "Show dangerous command" && echo "rm *"
Show dangerous command [y/N]?
还要注意,[y/N]?
是自动附加的。
默认值为“否”,因此不会回显任何内容。
重新提示,直到给出有效的响应:
$ 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 *
上面,我只是按下Enter键,所以命令运行了。
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]?
提示。
# 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
}
答案 17 :(得分:4)
受到@Mark和@Myrddin答案的启发,我为通用提示创建了这个功能
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"
答案 18 :(得分:4)
可以在POSIX shell中处理区域设置感知的“是/否选择”;通过使用LC_MESSAGES
语言环境类别的条目,女巫提供了现成的RegEx模式以匹配输入,并提供了本地化的字符串(是)。
#!/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
答案 19 :(得分:4)
我注意到没有人发布一个答案,显示了这种简单用户输入的多行回音菜单,所以这是我的去处:
#!/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
这个方法的发布是希望有人可能觉得它有用且节省时间。
答案 20 :(得分:4)
多选版本:
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
(在脚本中)。
答案 21 :(得分:3)
我建议你use dialog ......
Linux Apprentice: Improve Bash Shell Scripts Using Dialog
dialog命令允许在shell脚本中使用窗口框来使它们更具交互性。
它简单易用,还有一个名为gdialog的gnome版本,它采用完全相同的参数,但在X上显示它的GUI样式。
答案 22 :(得分:3)
更通用的是:
{{1}}
答案 23 :(得分:3)
执行此操作的一种简单方法是使用xargs -p
或gnu parallel --interactive
。
我更喜欢xargs的行为,因为它像其他交互式unix命令一样在提示之后立即执行每个命令,而不是收集在末尾运行的yes。 (在完成所需的操作后,可以按Ctrl-C进行操作。)
例如,
echo *.xml | xargs -p -n 1 -J {} mv {} backup/
答案 24 :(得分:3)
检查这个
read -p "Continue? (y/n): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1
答案 25 :(得分:2)
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!'
答案 26 :(得分:2)
我在这种情况下曾多次使用case
语句,使用案例陈述是一种很好的方法。可以实现使用布尔条件封装while
块的case
循环,以便更多地控制程序,并满足许多其他要求。满足所有条件后,可以使用break
将控制权传递回程序的主要部分。此外,为了满足其他条件,当然可以添加条件语句以伴随控制结构:case
语句和可能的while
循环。
使用case
语句来完成请求的示例
#! /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
答案 27 :(得分:2)
作为一线命令的朋友,我使用了以下内容:
#group3
写成longform,它的工作原理如下:
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=;
答案 28 :(得分:1)
#!/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
答案 29 :(得分:1)
回应其他人:
您不需要在BASH4中指定案例,只需使用&#39; ,,&#39;使var变为小写。另外,我强烈不喜欢将代码放入读取块内部,获取结果并在读取块IMO之外处理它。还包括一个&#39; q&#39;退出IMO。最后,为什么键入“是”&#39;只需使用-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
答案 30 :(得分:1)
这通常是我在脚本/函数中需要的:
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!"
答案 31 :(得分:1)
最简单的绝对解决方案是这种单线无巧妙技巧:
read -p "press enter ..." y
它使人想起经典的DOS Hit any key to continue
,除了它等待Enter键,而不仅仅是等待任何键。
是的,这不会为您提供“是”,“取消”的三个选项,但是在您接受control-C为“否”时很有用。在简单的脚本中取消,例如:
#!/bin/sh
echo Backup this project
read -p "press enter ..." y
rsync -tavz . /media/hard_to_remember_path/backup/projects/yourproject/
因为您不想记住丑陋的命令和路径,但是两种脚本都不会运行得太快,因此您没有机会在决定它不是要运行的脚本之前就停下来了。
答案 32 :(得分:0)
在大多数情况下,您需要继续执行脚本,直到用户继续输入“是”为止,并且仅在用户输入“否”时才停止。下面的代码片段将帮助您实现这一目标!
#!/bin/bash
input="yes"
while [ "$input" == "yes" ]
do
echo "execute script functionality here..!!"
echo "Do you want to continue (yes/no)?"
read input
done
答案 33 :(得分:-1)
如果您不介意在脚本中使用Python,则可以执行以下操作:
安装click
:
$ sudo pip install click
然后在脚本中:
#!/bin/bash
echo "[START]"
set -e
python3 -c '
import sys, click
if click.confirm("Continue?", default=True):
print("Yes")
else:
sys.exit(1)
'
set +e
echo "[END]"
示例输出:
[START]
Continue? [Y/n]:
Yes
[END]
除了Y/n
,您还只能以类似apt
的方式键入 Enter 。