1

I would like to list all directories in a directory. Some of them have spaces in their names. There are also files in the target directory, which I would like to ignore.

Here is the output of ls -lah data/:

drwxr-xr-x    5 me  staff   160B 24 Sep 11:30 Wrecsam - Wrexham
-rw-r--r--    1 me  staff    77M 24 Sep 11:31 Wrexham.csv
drwxr-xr-x    5 me  staff   160B 24 Sep 11:32 Wychavon
-rw-r--r--    1 me  staff    84M 24 Sep 11:33 Wychavon.csv

I would like to iterate only over the "Wrecsam - Wrexham" and "Wychavon" directories.

This is what I've tried.

for d in "$(find data -maxdepth 1 -type d -print | sort -r)"; do
    echo $d
done

But this gives me output like this:

Wychavon
Wrecsam
-
Wrexham

I want output like this:

Wychavon
Wrecsam - Wrexham

What can I do?

codeforester
  • 39,467
  • 16
  • 112
  • 140
Richard
  • 62,943
  • 126
  • 334
  • 542
  • @MatBailie No, it just doesn't descend into directories which are specified on the command line. – tripleee Oct 14 '18 at 18:18
  • You misunderstand. `ls f d` lists `f` and the *contents* of `d` whereas `ls -d f d` simply lists `f` and `d`. – tripleee Oct 14 '18 at 18:21

1 Answers1

2

Your for loop is not doing the right thing because of word splitting. You can use a glob instead of having to invoke an external command in a subshell:

shopt -s nullglob # make glob expand to nothing if there are no matches
for dir in data/*/; do
  echo dir="$dir"
done

Related:

codeforester
  • 39,467
  • 16
  • 112
  • 140
  • Thank you! This works, but (just to be annoying) I'd also like to list the directories in reverse order - is there a straightforward way to do that? – Richard Oct 14 '18 at 18:37
  • 1
    You could grab the directory names into an array with `dir_array=(data/*/)` and then sort the array following the steps mentioned in this post: [How to sort an array in Bash](https://stackoverflow.com/a/33359043/6862601). – codeforester Oct 14 '18 at 18:53