-2

在 Mac OS X 终端中使用 bash shell,我想将当前目录中的所有文件名放入一个变量中,每行一个名称(基本上是 ls -1 的输出)。但是,如果我这样做:

var=$(ls -1)
echo $var

变量 'var' 包含所有文件名,但在一行中,用空格分隔。我怎样才能解决这个问题并得到我想要的。更一般地说,这种行为的原因是什么?ls -1 扩容过程中发生了什么?

我意识到我可以通过执行以下操作将我想要的内容放入文件中,但我宁愿使用变量来实现相同的结果。

ls -1 > var

提前致谢。

4

1 回答 1

3

Your command var=$(ls -1) works fine. Try echo "$var" (with double quotes).

In echo $var, bash is reading $var and passing each word in as an argument to echo. It treats spaces and line breaks the same way. Using double quotes causes bash to treat $var as a single argument, rather than reformatting it.

As mklement0 mentioned, the expansion of $var that happens here is called word splitting. Search for "Word Splitting" in man bash for more information. The IFS variable (also in man bash) controls what characters bash uses to perform word splitting.

于 2015-02-16T22:49:40.613 回答