12

Let's say I have a directory with multiple subdirectories, each of which contains some files:

1/a.txt
1/b.txt
2/c.txt
2/d.txt
3/e.txt
3/f.txt

I want to see the size of each file. Please keep in mind, I know there are easier and more direct ways to do this, such as du -a. I just want to know why the following doesn't work, for educational purposes.


My pointless exercise

Running find . returns a list of all files and directories, so I tried piping it like so:

find . | xargs du

but that just returns the sizes of the directories 1, 2, and 3. I'm missing some bit of understanding, because in my mind xargs should be mapping each line of output from find to a call to du.


If instead I use:

find . | xargs du -a

then it works as expected, listing the sizes of all files and directories. It also works fine if I only pass it a list of files by using the -type f option, so it's something to do with receiving a list of directories mixed with files.

What's going on here?

1
  • 1
    you can also use find -exec du {} \; instead of piping to xargs
    – Sundeep
    Sep 1, 2016 at 5:41

3 Answers 3

14

What's going on is that xargs puts (if it can) all of the names on one command-line, so that you see only one command passed to du. Then du ignores the filenames (as you might expect: the files are part of the directories and it does not count those twice).

If you use a -n 1 parameter to xargs, it will split the command up and you will see something more as you expect.

find . | xargs -n 1 du -a

2
  • Oh look at that. I never actually looked at the output of xargs (I just started boning up on unix tools a couple weeks ago). So am I right in thinking the main use of xargs is for when you're piping in a very big list, or when the following command can't read from stdin?
    – philraj
    Aug 20, 2016 at 18:38
  • 1
    yes - and one use for the -n option is when you want only the ability to read stdin Aug 20, 2016 at 18:41
0

we can use below command

  find path -type f -printf "%s %p\n"
0

You could use the -exec function in find:

find . -type f -exec du -h {} \;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .