我想暂停shell脚本中的输入,并提示用户进行选择。标准的是、否或取消类型问题。如何在典型的bash提示符中完成此操作?
当前回答
您需要:
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选项向用户提示问题。
从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 ~/
这是我整理的东西:
#!/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
我是一个初学者,所以要谨慎对待,但它似乎奏效了。
我建议你使用对话框。。。
Linux学徒:使用对话框改进Bash Shell脚本对话框命令允许在shell脚本中使用窗口框,以使其使用更具交互性。
它简单易用,还有一个名为gdialog的gnome版本,它采用了完全相同的参数,但在X上显示了GUI风格。
这个问题有很多很好的答案,但从我看来,没有一个是我的理想,那就是:
简单一点,只需要几行外壳使用单个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。
多选版本:
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(在脚本中)。