一个简单的 if/else bash 脚本,它对用户的是/否输入做出反应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11373702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
A simple if/else bash script which reacts to user's yes/no input?
提问by sandalone
I basically have a bash script which executes 5 commands in a row. I want to add a logic which asks me "Do you want to execute command A" and if I say YES, the command is executed, else the script jumps to another line and I see the prompt "Do you want to execute command B".
我基本上有一个 bash 脚本,它连续执行 5 个命令。我想添加一个逻辑,询问我“您是否要执行命令 A”,如果我说“是”,则执行该命令,否则脚本跳转到另一行,我会看到提示“您要执行命令 B”吗? .
The script is very simple and looks like this
脚本非常简单,看起来像这样
echo "Running A"
commandA &
sleep 2s;
echo "done!"
echo "Running B"
commandB &
sleep 2s;
echo "done!"
...
回答by Mat
Use the readbuiltin to get input from the user.
使用read内置函数从用户那里获取输入。
read -p "Run command $foo? [yn]" answer
if [[ $answer = y ]] ; then
# run the command
fi
Put the above into a functionthat takes the command (and possibly the prompt) as an argument if you're going to do that multiple times.
把上面成一个功能是接收命令(也可能是提示)作为参数,如果你要的是多次做。
回答by Todd A. Jacobs
You want the Bash read builtin. You can perform this in a loop using the implicit REPLYvariable like so:
您希望 Bash读取内置. 您可以使用隐式REPLY变量在循环中执行此操作,如下所示:
for cmd in "echo A" "echo B"; do
read -p "Run command $cmd? "
if [[ ${REPLY,,} =~ ^y ]]; then
eval "$cmd"
echo "Done!"
fi
done
This will loop through all your commands, prompt the user for each one, and then execute the command only if the first letter of the user's response is a Y or y character. Hope that helps!
这将遍历您的所有命令,为每个命令提示用户,然后仅当用户响应的第一个字母是 Y 或 y 字符时才执行该命令。希望有帮助!

