Shell脚本:提示用户输入时出现问题

时间:2014-01-08 19:59:50

标签: shell sh

我在“How do I prompt for Yes/No/Cancel input in a Linux shell script?”中回答这个问题。

代码:

state="CA"
city="Los Angeles"
while true; do
    read -e -p "State: " -i $state state
    read -e -p "City: " -i $city city
    echo "Your state: $state"
    echo "Your city: $city"
done

这就是它的运行方式。

$ ./test.sh
State: CA
City: Los
Your state: CA
Your city: 
State: DE
City: city
Your state: DE
Your city: 

第一个输入:城市未正确显示

第一个输出:我没有输入城市,所以它应该显示“Los”,对吗?

第二个输入:状态变为“DE”,效果很好,这意味着shell支持

但是城市默认为“城市”,我再次没有输入

第二输出:城市不正确

无论如何,我认为问题在于“洛杉矶”的空间。如何解决?

非常感谢!

额外信息

这是我正在使用的bash。

$ bash --version
GNU bash, version 4.2.25(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

找到答案

应该在-i中使用引用,例如

read -e -p "City: " -i "$city" city

2 个答案:

答案 0 :(得分:4)

read -e -p "City: " -i $city city

$city有空格,因此-i为'Los'而不是'Angeles'

因此Angeles将是由read

设置的变量

答案 1 :(得分:2)

你对这个问题的看法是正确的;你有关于如何在你面前解决它的信息......

read -e -p "City: " -i "$city" city