-2

Using the bash shell in the Mac OS X terminal, I want to put inside a variable all the filenames in the current directory, with one name per line (basically, the output of ls -1). However, if I do:

var=$(ls -1)
echo $var

Variable 'var' contains contains all the filenames, but on a single line, separated with spaces. How can I fix this and get what I want. More generally, what is the reason of this behavior? What is going on during the expansion of ls -1?

I realize that I could put what I want inside a file by doing the following, but I would rather achieve the same result with a variable.

ls -1 > var

Thanks in advance.

user3781201
  • 1,261
  • 2
  • 9
  • 7
  • 1
    But why do you want to do this??? what are you going to do with this variable??? – gniourf_gniourf Feb 16 '15 at 22:59
  • Thank you so much for the explanations! Although I simplified my question by using `ls`, I actually intend to use `stat`. My goal is to write a script that will - look through all the files in a directory sorted by creation date - identify all subgroups of files created less than x seconds apart - make for each subgroup a subdirectory named after the creation date of the earliest file (YYMMDD-HHMMSS) - move each subgroup into its subdirectory Therefore, I need a table with two columns: file birth as Unix time (available in Mac OSX's version of `stat`) and file name. – user3781201 Feb 17 '15 at 01:25
  • possible duplicate of [How do I echo $command without breaking the layout](http://stackoverflow.com/questions/2684216/how-do-i-echo-command-without-breaking-the-layout) – tripleee Feb 17 '15 at 11:02

1 Answers1

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.

yellowantphil
  • 1,483
  • 5
  • 21
  • 30
  • 1
    Indeed; also worth mentioning that what happens here (splitting the value into words by whitespace and thus passing multiple arguments) is called _word splitting_, which is _one_ of the so-called _expansions_ that bash performs on unquoted variable references (search for `Word Splitting` in `man bash`, or, more generally, `EXPANSIONS`). – mklement0 Feb 16 '15 at 22:59