Pau*_*ce. 893
read -p "Are you sure? " -n 1 -r
echo # (optional) move to a new line
if [[ $REPLY =~ ^[Yy]$ ]]
then
# do dangerous stuff
fi
Run Code Online (Sandbox Code Playgroud)
我结合levislevis85的建议(感谢!),并添加-n选项,以read接受,而不需要按一个字符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
Run Code Online (Sandbox Code Playgroud)
然而,正如Erich所指出的,在某些情况下,例如由于脚本在错误的shell中运行而导致的语法错误,否定的形式可能允许脚本继续"危险的东西".失败模式应该有利于最安全的结果,因此只if应使用第一个,不被否定的.
说明:
该read命令输出prompt(-p "prompt")然后接受一个字符(-n 1)并逐字接受反斜杠(-r)(否则read会将反斜杠视为转义并等待第二个字符).read存储结果的默认变量是,$REPLY如果您不提供如下名称:read -p "my prompt" -n 1 -r my_var
该if语句使用正则表达式来检查$REPLYmatches(=~)中的字符是大写还是小写"Y".这里使用的正则表达式是"一个字符串starting(^),它只包含一个括号表达式([Yy])和结束($)" 中的一个字符列表.锚(^和$)防止匹配更长的字符串.在这种情况下,它们有助于强化命令中的单字符限制集read.
否定形式使用逻辑"not"运算符(!)匹配(=~)任何不是"Y"或"y"的字符.表达这种情况的另一种方式是可读性较差,并且在这种情况下我并未明确表达我的意图.但是,这就是它的样子:if [[ $REPLY =~ ^[^Yy]$ ]]
gho*_*g74 161
用例/ esac.
read -p "Continue (y/n)?" choice
case "$choice" in
y|Y ) echo "yes";;
n|N ) echo "no";;
* ) echo "invalid";;
esac
Run Code Online (Sandbox Code Playgroud)
优点:
Ada*_*upp 33
试试readshell内置:
read -p "Continue (y/n)?" CONT
if [ "$CONT" = "y" ]; then
echo "yaaa";
else
echo "booo";
fi
Run Code Online (Sandbox Code Playgroud)
Ser*_*ujo 31
通过这种方式,您可以得到"是"或"输入"
read -r -p "Are you sure? [Y/n]" response
response=${response,,} # tolower
if [[ $response =~ ^(yes|y| ) ]] || [[ -z $response ]]; then
your-action-here
fi
Run Code Online (Sandbox Code Playgroud)
如果你使用zsh试试这个:
read "response?Are you sure ? [Y/n] "
response=${response:l} #tolower
if [[ $response =~ ^(yes|y| ) ]] || [[ -z $response ]]; then
your-action-here
fi
Run Code Online (Sandbox Code Playgroud)
Séb*_*rra 20
这是我使用的功能:
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
}
Run Code Online (Sandbox Code Playgroud)
并使用它的一个例子:
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...
Run Code Online (Sandbox Code Playgroud)
我希望你喜欢,
干杯!
Tom*_*Tom 17
这是我在别处找到的,是否有更好的版本?
read -p "Are you sure you wish to continue?"
if [ "$REPLY" != "yes" ]; then
exit
fi
Run Code Online (Sandbox Code Playgroud)
[[ -f ./${sname} ]] && read -p "File exists. Are you sure? " -n 1
[[ ! $REPLY =~ ^[Yy]$ ]] && exit 1
Run Code Online (Sandbox Code Playgroud)
在函数中使用它来查找现有文件并在覆盖之前提示.
小智 5
echo are you sure?
read x
if [ "$x" = "yes" ]
then
# do the dangerous stuff
fi
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
330871 次 |
| 最近记录: |