DEV Community

David Cao
David Cao

Posted on

check size of directory in Linux

Introduction

Linux is one of the most popular operating systems in the world. It is Unix-like, and it is also open-source. Quite a big percentage of developers use Linux because it can be customized in so many ways.

What's cool about Linux is its command line. Every 'hackers' paradise. There are a ton of commands. If you aren't familiar with any Linux commands, be sure to check out this post on the Linux Commands Everyone Should Know.

There is probably a command for almost anything that you want to do. For example what if you wanted to get the size of a directory? Well luckily for you there is a command for that. In this post, we are going to talk about that command and see what it can offer.

The du command

This command lets the user get a quick view of the disk usage. The best way to use it is by giving it the directory you want to see the size of. It should look a little something like this:
du directory_name

// output
2314 directory_name

This will give you the size of all the files and at the very end, it will give you the size of the directory itself. You could point out the full path, or you could just give the name of the directory you want to see if you are already on the same path.

But we could make this even easier just b adding 2 flags. Flags help the command change its behavior. For the du command we could add the flags -s and -h.

  1. -s stands for summarize and it will show you only the total size of the directory, without all those files popping up on your screen.
  2. -h stands for human-readable and it will convert the size so that you can read it easier. Just by running the command without the -h flag doesn't specify you a unit of measurement.

So now to get the best of this command, you should run it like this with the -s and -h flags:
du -sh directory_name

// output
44.5M directory_name
And if you wanted to see all of the directories sizes, you could just run this:
du -sh ./*

// output
12.2M dir1
2.5M dir2
55M dir3

Another thing you can do is use pipe(|) and sort them by size, which will make it even easier for you to see their sizes. What | does is get the output from the command behind it and add it into the input of the command after it. So to sort the directories by size just run the following command:
du -sh ./* | sort -h

// output
55M dir3
12.2M dir1
2.5M dir2

Conclusion

This is a pretty useful command that I think everybody should know, just because of how short and easy it is. I hope that this post has helped you and I wish you happy coding.

Top comments (0)