Bash:在命令行上使用空格输入保留字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24337385/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:43:32  来源:igfitidea点击:

Bash: preserve string with spaces input on command line?

stringbashinput

提问by asking

I'd like to allow a string to be captured with spaces, so that:

我想允许用空格捕获字符串,以便:

echo -n "Enter description: "
read input
echo $input

Would produce:

会产生:

> Enter description: My wonderful description!
> My wonderful description!

Possible?

可能的?

回答by Gordon Davisson

The main thing to worry about is that when you refer to a variable without enclosing it in double-quotes, the shell does word splitting (splits it into multiple words wherever there's a space or other whitespace character), as well as wildcard expansion. Solution: use double-quotes whenever you refer to a variable (e.g. echo "$input").

需要担心的主要问题是,当您引用一个变量而不用双引号将其括起来时,shell 会进行分词(在有空格或其他空白字符的地方将其拆分为多个词)以及通配符扩展。解决方案:无论何时引用变量(例如echo "$input"),都使用双引号。

Second, readwill trim leading and trailing whitespace (i.e. spaces at the beginning and/or end of the input). If you care about this, use IFS= read(this essentially wipes out its definition of whitespace, so nothing gets trimmed). You might also want to use read's -r("raw") option, so it doesn't try to interpret backslash at the end of a line as a continuation character.

其次,read将修剪前导和尾随空格(即输入开头和/或结尾的空格)。如果您关心这一点,请使用IFS= read(这基本上消除了其对空白的定义,因此没有任何内容被修剪)。您可能还想使用read's -r("raw") 选项,因此它不会尝试将行尾的反斜杠解释为连续字符。

Finally, I'd recommend using read's -poption to supply the prompt (instead of echo -n).

最后,我建议使用read's-p选项来提供提示(而不是echo -n)。

With all of these changes, here's what your script looks like:

通过所有这些更改,您的脚本如下所示:

IFS= read -r -p "Enter description: " input
echo "$input"