0

I want to list the size of directories under a given root (using du -hs) . The issue is that where the directory names have spaces the du command is getting each word of the name as a whole directory name.

I tried to fix this by quoting the output through xargs but the output is the same.

#!/bin/bash

root="$1"
echo "Searching in $root"
for d in $(find $root -maxdepth 1 -type d | xargs -i echo "'{}'")
  do 
    #
    # the root directory can take a long time so let's skip it
    #
    if [ "$d" != "$root" ] 
      then
         echo "Looking at directory $d"
         echo $(du -hs "$d")
      fi
  done
2
  • 1
    You don't want to remove the spaces if they're part of the filenames. The result would be a different filename. Instead you want to keep the filenames intact, but separate. But the thing is that the shell doesn't make it too easy to do that the way you hope to do it. Some mandatory reading linked. Commented Jul 30, 2021 at 14:40
  • @ilkkachu Exactly. I thought I was doing that with '{}'. Guess not. I was not trying to remove the spaces. Commented Jul 30, 2021 at 17:01

1 Answer 1

2

Because of exactly the issue you describe, it is disrecommended to iterate over the output of find. Instead, you should use the -exec option if that is available to your version of find:

find "$root" -maxdepth 1 -type d -exec du -hs {} \;

To exclude the $root directory, you can add mindepth:

find "$root" -mindepth 1 -maxdepth 1 -type d -exec du -hs {} \;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.