为什么双引号会影响linux中这些echo语句的打印?

我正在捕获ps aux的输出:

current_processes=`ps aux | grep "tempdir" | tail -3`

当我回应它时,它看起来像这样

echo $current_processes
19984 10089 17784

当我回声加双引号时,它看起来像这样:

echo "$current_processes"
19984 
10089
17784    

当我使用双引号但没有双引号时,为什么它会将这些放在新行上?

最佳答案
效果来自shell.如果没有双引号,shell会用空格替换换行符,制表符和空格.您可以使用双引号来避免这种替换.有关更多详细信息,请参阅bash(1)手册页中的Word拆分部分:

Word Splitting

The shell scans the results of parameter expansion, command substitution, and arithmetic expansion that did not occur within
double quotes for word splitting.

The shell treats each character of IFS as a delimiter, and splits the
results of the other expansions into words on these characters. If IFS
is unset, or its value is exactly , the default,
then any sequence of IFS characters serves to delimit words. If IFS
has a value other than the default, then sequences of the whitespace
characters space and tab are ignored at the beginning and end of the
word, as long as the whitespace character is in the value of IFS (an
IFS whitespace character). Any character in IFS that is not IFS white-
space, along with any adjacent IFS whitespace characters, delimits a
field. A sequence of IFS whitespace characters is also treated as a
delimiter. If the value of IFS is null, no word splitting occurs.

您可以使用echo“$IFS”|查看IFS的内容XXD.它会告诉你

00000000: 2009 0a0a                                 ...

这意味着空格(0x20),制表符(0x09)和换行符(0x0a).第二个0x0a来自echo命令.

您可以通过将IFS设置为空字符串来避免此替换:

IFS=""
echo "$current_processes"
19984 
10089
17784

但我不建议这样做.

转载注明原文:为什么双引号会影响linux中这些echo语句的打印? - 代码日志