对 bash 脚本中用户输入的建议答案
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4479987/
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
Suggest answer to user input in bash scripting
提问by Larry Cinnabar
Here is an example:
下面是一个例子:
#!/bin/bash
echo -e "Enter IP address: \c"
read
echo $REPLY
But I want to make it easier for the user to answer. I'd like to offer an answer to the user. It should look something like this:
但我想让用户更容易回答。我想为用户提供一个答案。它应该是这样的:
Enter your IP: 192.168.0.4
输入您的 IP:192.168.0.4
And the user can just press Enter and agree with 192.168.0.4, or can delete some characters (for example delete "4" with one backspace and type 3 instead).
用户只需按 Enter 并同意 192.168.0.4,也可以删除一些字符(例如删除“4”并用一个退格键键入 3)。
How to make such an input? It is possible in bash?
如何进行这样的输入?在 bash 中可能吗?
回答by Martin v. L?wis
bash's read has readline support (Edit: Jonathan Leffler suggests to put the prompt into read as well)
bash 的 read 具有 readline 支持(编辑:Jonathan Leffler 建议也将提示放入 read)
#!/bin/bash
read -p "Enter IP address: " -e -i 192.168.0.4 IP
echo $IP
回答by SiegeX
The way I would do this is to suggest the default in the prompt in brackets and then use the default valueparameter expansion to set IPto 192.168.0.4 if they just pressed enter, otherwise it will have the value they entered.
我这样做的方法是在括号中的提示中建议默认值,然后使用默认值参数扩展设置IP为 192.168.0.4,如果他们只是按回车键,否则它将具有他们输入的值。
#!/bin/bash
default=192.168.0.4
read -p "Enter IP address [$default]: " IP
IP=${IP:-$default}
echo "IP is $IP"
Output
输出
$ ./defip.sh
Enter IP address [192.168.0.4]:
IP is 192.168.0.4
$ ./defip.sh
Enter IP address [192.168.0.4]: 192.168.1.1
IP is 192.168.1.1
回答by Jonathan Leffler
The classic way to do most of what you want is:
做你想做的大部分事情的经典方法是:
default="192.168.0.4"
echo -e "Enter IP address ($default): \c"
read reply
[ -z "$reply" ] && reply=$default
echo "Using: $reply"
This doesn't give the editing option.
这不提供编辑选项。
回答by Ben Hymanson
Editing isn't practical but it's common to do something like:
编辑并不实用,但通常执行以下操作:
echo -e "Enter IP address [$default]: \c"
read answer
if [ "$answer" = "" ]; then
answer="$default"
fi

