So I want to sum and display the sum of the size of the files that are solely included in directory1 but not in directory2. However, according to my code, this is done for only one file of the directory, how can I make it work for multiple files? The code below is where the problem is found:


echo Files that are included only in directory1 and not in directory2
diff $dir1 $dir2 | egrep $dir1 | wc -l
diff $dir1 $dir2 | egrep $dir1 
files=$(diff $dir1 $dir2 |egrep $dir1 |awk '{print $4}')
ls -l ./$dir1/$files | awk '{t+=$5}END{print t}'
  • du -c file [file..] will give you the sum of the disk space used by the arguments (or the sum of their file size if you use --apparent-size). It can also use an exclusion list (-exclude-from=FILE), so you could call it on dir1 using the dir2 contents as the exclusion list...
    – xenoid
    Commented Dec 23, 2019 at 17:34
  • @xenoid thank you for responding could you please explain it with a command? So it would be something like du -c -exclude-from=$dir2?
    – user25
    Commented Dec 23, 2019 at 17:38
  • Please see full answer
    – xenoid
    Commented Dec 23, 2019 at 17:55
  • @xenoid I get 0
    – user25
    Commented Dec 23, 2019 at 18:04
  • What exact command did you use? And if you are using the answer please comment on the answer.
    – xenoid
    Commented Dec 23, 2019 at 18:07

1 Answer 1


Best use du for this:

du -s directory reports the size used by all files and subdirectories. You can give du a exclusion list with --exclude-from, so in your case this exclusion list would be the names of the files in dir2, that can be easily obtained with basename -a dir2/*. --exclude-from requires a file, but we don't need to create a true file, we can use "process substitution. Putting it all together:

du --exclude-from <(basename -a dir2/*) -s dir1 

There are du options to report the size in bytes, KB, or MB, and you can also ask it to report the disk usage (default) or the size as reported by ls (which is not the same for sparse files).

For instance, starting with:

├── dir1
│   ├── file1
│   ├── file2
│   ├── file3
│   ├── file4
│   └── file5
└── dir2
    ├── file5
    └── file6

du -c dir1/* reports:

10240   dir1/file1
10240   dir1/file2
10240   dir1/file3
10240   dir1/file4
51200   dir1/file5
92160   total

Excluding dir2 files will exclude file5 and so the size should be 50MB less:

> du --exclude-from <(basename -a dir2/*) -s dir1
40964   dir1
  • Comments are not for extended discussion; this conversation has been moved to chat.
    – terdon
    Commented Dec 24, 2019 at 11:13

You must log in to answer this question.

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