如何在bash脚本中提示用户进行确认?
read -p "Are you sure? " -n 1 -r
echo # (optional) move to a new line
if [[ $REPLY =~ ^[Yy]$ ]]
then
# do dangerous stuff
fi
编辑:
我纳入levislevis85的建议(感谢!),并且增加了-n
选项read
接受一个字符,而不需要按输入。您可以使用其中的一个或两个。
而且,否定形式可能是这样的:
read -p "Are you sure? " -n 1 -r
echo # (optional) move to a new line
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1 # handle exits from shell or function but don't exit interactive shell
fi
然而,随着由Erich指出,在某些情况下,如造成错误的壳中运行该脚本语法错误,否定形式可以让脚本继续“危险的东西”。失败模式应该支持最安全的结果,因此只应使用第一个非否定if
。
QND:使用
read VARNAME
echo $VARNAME
为无的readline支持一个行响应。然后测试$ VARNAME,但是你想要的。
echo are you sure?
read x
if [ "$x" = "yes" ]
then
# do the dangerous stuff
fi
尝试read
外壳内置:
read -p "Continue (y/n)?" CONT
if [ "$CONT" = "y" ]; then
echo "yaaa";
else
echo "booo";
fi
#!/bin/bash
echo Please, enter your name
read NAME
echo "Hi $NAME!"
if [ "x$NAME" = "xyes" ] ; then
# do something
fi
我是个简短的脚本来读取bash和回显的结果。
这是我在别处找到的,是否有更好的版本?
read -p "Are you sure you wish to continue?"
if [ "$REPLY" != "yes" ]; then
exit
fi
用例/ esac。
read -p "Continue (y/n)?" choice
case "$choice" in
y|Y) echo "yes";;
n|N) echo "no";;
*) echo "invalid";;
esac
优势:
- 整洁
- 可以用 “OR” 条件更容易
- 可以使用字符范围,如[YY] [EE] [SS]接受词 “是” ,其中任何字符可以是小写或大写。
[[ -f ./${sname} ]] && read -p "File exists. Are you sure? " -n 1
[[ ! $REPLY =~ ^[Yy]$ ]] && return 1
使用这一个功能,查找现有的文件,并覆盖前提示。
解析器抱怨'返回'外的函数,你可能是'退出'。我仍然喜欢你的答案,因为如果确认它不缩进要执行的代码。 – dhill 2017-02-17 20:30:42
这样,你得到 'Y' '是' 或 '回车'
read -r -p "Are you sure? [Y/n]" response
response=${response,,} # tolower
if [[ $response =~ ^(yes|y|) ]] || [[ -z $response ]]; then
your-action-here
fi
不接受默认Y – 2015-02-20 14:43:10
对于默认Y 如果[[$ response =〜^(yes | y |)]]] | [-z $ response];然后 – 2015-02-20 14:48:38
这是我使用的功能:用它
function ask_yes_or_no() {
read -p "$1 ([y]es or [N]o): "
case $(echo $REPLY | tr '[A-Z]' '[a-z]') in
y|yes) echo "yes" ;;
*) echo "no" ;;
esac
}
和示例:
if [[ "no" == $(ask_yes_or_no "Are you sure?") || \
"no" == $(ask_yes_or_no "Are you *really* sure?") ]]
then
echo "Skipped."
exit 0
fi
# Do something really dangerous...
- 输出总是“是”或“否”
- 这是“没有”默认
- 惟独没有“Y”或“是”返回“无”,所以这是一个危险的bash脚本
- 很安全,这是不区分大小写,“Y”,“是”,或“是”工作为“是”。
我希望你喜欢它,
干杯!
[相关](http://stackoverflow.com/questions/3231804/in-bash-how-to-add-are-you-sure-yn-to-any-command-or-alias) – 2013-08-04 21:20:14