0

I'm trying to cache list of files in a variable:

files=`ls -1 | head -2`
echo $files

So that if there's only one file -- use it:

files=`ls -1 | head -2`
numberOfFiles=`echo $files | wc -l`

if [ $numberOfFiles == 1 ]; then
  echo "Using $files"
else
  echo "ERROR: Too many files:\n$files\nI don't know which one to take."
fi

But much to my surprise echo $files does not preserve new lines of ls -1 output. So $numberOfFiles is always 1.

How do I store multiline output of ls -1 in a variable?

Adobe
  • 12,967
  • 10
  • 85
  • 126
  • It works fine with `zsh` but there is an issue with `bash` prompt, since `ls -1` prints directories in 1 line when we do files=`ls -1` but prints in a new line if we just execute `ls -1`. – dkb Dec 26 '18 at 05:51
  • edited: sorry, missunderstood. – wuseman Dec 26 '18 at 06:39
  • 1
    The biggest problem is not quoting the variable reference (use `echo "$files"` instead of `echo $files`), but I'd also recommend against [parsing `ls` to get a list of files](https://mywiki.wooledge.org/ParsingLs). – Gordon Davisson Dec 26 '18 at 08:41
  • @GordonDavisson. Thanks for the link. – Adobe Dec 26 '18 at 10:19

0 Answers0