我如何提示在bash脚本用户确认? [英] How do I prompt a user for confirmation in bash script?

查看:377
本文介绍了我如何提示在bash脚本用户确认?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提出一个快速的你确定吗?提示在有潜在危险的bash脚本的顶部确认,什么是做到这一点的最简单/最佳方法是什么?


解决方案

 阅读-p你确定吗?-n 1 -r
回声#(可选)移动到一个新行
如果[[$ REPLY =〜^ [YY] $]
然后
    #做的东西危险
科幻

修改

我注册的 levislevis85 的建议(感谢!),并添加 -n 选项来接受一个字符,而不需要preSS <大骨节病>输入。您可以使用其中的一个或两个。

此外,否定形式可能是这样的:

 阅读-p你确定吗?-n 1 -r
回声#(可选)移动到一个新行
如果[! $ REPLY =〜^ [YY] $]
然后
    1号出口
科幻

不过,正如由Erich指出,在某些情况下,如造成脚本语法错误,在错误的外壳正在运行,则否定形式可以让脚本继续以危险的东西。失效模式应有利于最安全的结果,所以只有第一,非否定如果应该被使用。

I want to put a quick "are you sure?" prompt for confirmation at the top of a potentially dangerous bash script, what's the easiest/best way to do this?

解决方案

read -p "Are you sure? " -n 1 -r
echo    # (optional) move to a new line
if [[ $REPLY =~ ^[Yy]$ ]]
then
    # do dangerous stuff
fi

Edit:

I incorporated levislevis85's suggestion (thanks!) and added the -n option to read to accept one character without the need to press Enter. You can use one or both of these.

Also, the negated form might look like this:

read -p "Are you sure? " -n 1 -r
echo    # (optional) move to a new line
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
    exit 1
fi

However, as pointed out by Erich, under some circumstances such as a syntax error caused by the script being run in the wrong shell, the negated form could allow the script to continue to the "dangerous stuff". The failure mode should favor the safest outcome so only the first, non-negated if should be used.

这篇关于我如何提示在bash脚本用户确认?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆