1

I've found a few similar questions to this but surprisingly none of them work for me.

I have this written in a script:

for d in $(ls -d "$1"); do echo $d done

$1 is the parent directory for which I wish to print out the list of subdirectories for, however, running this prints out, for example, a directory named "dir with spaces" as 3 words on separate lines.

Lost Crotchet
  • 1,270
  • 12
  • 17
  • I must say - I have never come across a problem like this in my career so far; usually for something seemingly simple but irritating, I will have to spend 10-30 mins maximum doing research and i'll find a solution, but this one has really got me! – Lost Crotchet Aug 28 '18 at 23:43
  • 1
    Try the find command. – Jim Janney Aug 28 '18 at 23:59
  • 2
    See [BashFAQ #20: "How can I find and safely handle file names containing newlines, spaces or both?"](http://mywiki.wooledge.org/BashFAQ/020), and also ["Why you shouldn't parse the output of `ls`"`](http://mywiki.wooledge.org/ParsingLs). – Gordon Davisson Aug 29 '18 at 01:48
  • If you just want directories, you can use a glob ending with `/`: `for d in "$1"/*/; do echo "$d"; done – rici Aug 29 '18 at 04:41

1 Answers1

5

You can use shell globbing instead of process substitution, which doesn't suffer from word expansion problem:

# to include dotfiles and not iterate empty directory
shopt -s dotglob nullglob

for d in "$1"/*; do
    echo "$d"
done

Or you can resort to pretty common find ... -print0 | xargs -0 ... pattern.

weirdan
  • 2,499
  • 23
  • 27
  • 1
    Use `shopt -s nullglob` to handle empty directories correctly. `printf '%s\n' "$d"` is safer then `echo "$d"` (see [What is more portable? echo -e or using printf?](https://stackoverflow.com/q/11530203/4154375)). – pjh Aug 29 '18 at 17:03
  • Everything goes well except I get "shopt: not found" – Lost Crotchet Aug 29 '18 at 19:54
  • actually I just realised that's because I was running the script with 'sh' instead of 'bash'. In that case this works pretty well, thanks! – Lost Crotchet Aug 29 '18 at 19:58