14

The default behavior of du on my system is not the proper default behavior.

If I ls my /data folder, I see (removing the stuff that isn't important):

ghs ghsb -> ghs hope rssf -> roper roper 

Inside each folder is a set of folders with numbers as names. I want to get the total size of all folders named 14, so I use:

du -s /data/*/14 

And I see...

161176 /data/ghs/14 161176 /data/ghsb/14 8 /data/hope/14 681564 /data/rssf/14 681564 /data/roper/14 

What I want is only:

161176 /data/ghs/14 8 /data/hope/14 681564 /data/roper/14 

I do not want to see the symbolic links. I've tried -L, -D, -S, etc. I always get the symbolic links. Is there a way to remove them?

4 Answers 4

19

This isn't du resolving the symbolic links; it's your shell.

* is a shell glob; it is expanded by the shell before running any command. Thus in effect, the command you're running is:

du -s /data/ghs/14 /data/ghsb/14 /data/hope/14 /data/rssf/14 /data/roper/14 

If your shell is bash, you don't have a way to tell it not to expand symlinks. However you can use find (GNU version) instead:

find /data -mindepth 2 -maxdepth 2 -type d -name 14 -exec du -s {} + 
2
10

Make du skip symbolic links:

du isn't smart enough to not chase links. By default find will skip symlinks. So creating an unholy alliance between find, du, and awk, the proper dark magic incantation becomes:

find /home/somedirectory/ -exec du -s {} + | awk '{total = total + $1}END{print total}' 

Produces:

145070492

To force the output to be human readable:

find /home/somedirectory/ -exec du -s {} + | awk '{total = total + $1}END{print (total / 1024 / 1024) "MB"}' 

Produces:

138.35MB

What's going on here:

/home/somedirectory/ directory to search. -exec du -s + run du -s over the results, producing bytes awk '...' get the first token of every line and add them up, dividing by 1024 twice to produce MB 
3
  • 1
    should be cat /tmp/tmp.txt Commented Apr 26, 2019 at 16:00
  • What if one wanted to exclude certain directories (in my case /home/user and /media? Commented Sep 8, 2022 at 1:23
  • Please specify du -b (binary size) to avoid wrong size reporting. default du report the size in BLOCK (which can be 512 or 1024 ecc) Commented Dec 3, 2022 at 18:22
3

Simply use the flag -L:

From the man page:

-L, --dereference dereference all symbolic links 

Then du calculates the size no matter whether they are symbolic or not.

2
  • 3
    This would not stop the * glob used on the command line from matching symbolic links. Commented Jan 13, 2021 at 13:11
  • Although I don't think this answers the question, it is exactly what I needed. Thank you! Commented May 31, 2023 at 5:56
1
du -P 

-P, --no-dereference don't follow any symbolic links (this is the default)

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.