我想在可能存在风险的bash脚本顶部添加一个快速的“您确定吗?”提示以便确认,最简单/最好的方法是什么?
我想在可能存在风险的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 的建议(谢谢!),并在 read
中添加了 -n
选项,以接受一个字符而无需按下 Enter 键。您可以使用其中一个或两个选项。
此外,否定形式可能如下所示:
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
if
。read
命令输出提示(-p "prompt"
),然后接受一个字符(-n 1
)并按原样接受反斜杠(-r
)(否则read
将把反斜杠视为转义符并等待第二个字符)。如果您没有提供名称(例如read -p "my prompt" -n 1 -r my_var
),则默认变量用于存储read
的结果是$REPLY
。
if
语句使用正则表达式来检查$REPLY
中的字符是否匹配(=~
)大写或小写的“Y”。这里使用的正则表达式表示“以括号表达式([Yy]
)中的字符列表之一开头(^
)且完全由该字符组成($
)的字符串”。锚点(^
和$
)防止匹配更长的字符串。在这种情况下,它们有助于加强read
命令中设置的一个字符限制。!
)来匹配(=~
)任何不是“Y”或“y”的字符。另一种表达方式不太可读,而且在我看来并没有清楚地表达出意图。然而,这是它的样子:if [[ $REPLY =~ ^[^Yy]$ ]]
。sh
shell 中运行它,那么存在读取和条件测试 [[ 失败但脚本仍将继续执行而不退出的风险——这可能不是您想要的,因此正面版本更安全。 - ErichBSchulz[[ $REPLY =~ ^[Yy]$ ]] || exit -1
? 如果在旧版本的shell中运行,它会如何评估? - Scolytus用例/结束用例。
read -p "Continue (y/n)?" choice
case "$choice" in
y|Y ) echo "yes";;
n|N ) echo "no";;
* ) echo "invalid";;
esac
优点:
echo "Quitting script."; exit;;
来退出脚本。但是,如果输入为 yes,则脚本将继续执行 esac
后面的内容。 - Alaa Alin|N ) echo "no"; return;;
,那么如果你输入 'n',脚本将在此结束,否则将继续执行,这是你的意思吗? - Rellikiox尝试使用read
shell内置命令:
read -p "Continue (y/n)?" CONT
if [ "$CONT" = "y" ]; then
echo "yaaa";
else
echo "booo";
fi
这样你会得到“是”、“yes”或者“Enter”
read -r -p "Are you sure? [Y/n]" response
response=${response,,} # tolower
if [[ $response =~ ^(y| ) ]] || [[ -z $response ]]; then
your-action-here
fi
如果您正在使用 zsh,请尝试以下操作:
read "response?Are you sure ? [Y/n] "
response=${response:l} #tolower
if [[ $response =~ ^(y| ) ]] || [[ -z $response ]]; then
your-action-here
fi
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...
这是我在其他地方找到的,有更好的版本可能吗?
read -p "Are you sure you wish to continue?"
if [ "$REPLY" != "yes" ]; then
exit
fi
[[ -f ./${sname} ]] && read -p "File exists. Are you sure? " -n 1
[[ ! $REPLY =~ ^[Yy]$ ]] && exit 1
我在一个函数中使用了这个功能来查找现有的文件并在覆盖之前提示。
echo are you sure?
read x
if [ "$x" = "yes" ]
then
# do the dangerous stuff
fi
#!/bin/bash
echo Please, enter your name
read NAME
echo "Hi $NAME!"
if [ "x$NAME" = "xyes" ] ; then
# do something
fi
qnd:使用
read VARNAME
echo $VARNAME
如果需要一行响应而没有 readline 支持, 那么可以使用以下命令。之后,您可以按照自己的方式测试 $VARNAME。