The ls command on Linux is used to list all the contents of any directory. However, to display more options and to sort all the directories by size, we have to use a different command known as du. In this tutorial, we will discuss this command in detail, and we will also take a look at how can we incorporate different tools such as the head, tail and sort utilities to make it easier for us to read the output.
List all directories with the du command
The du command by default lists all the directories and subdirectories recursively, so unless you want to spam your Terminal with a huge output, you should use this command with several options, especially if the current directory has a lot of subdirectories.
You can run the du command like this :
Here, -h option signifies ‘Human Readable’, therefore the output of the command will be in a format which is easier to read by the user.
As you can see, the output of the command is still not sorted by size, and we have the size of all the directories in a recursive manner. To limit the command so that it does not go deep into the directory structure, you can use –max-depth=N option along with the du command.
du -h --max-depth=1
Sorting directories by size
To list all directories and sort them by size, you can pipe the output of this command and pass it through the sort utility like this :
du -h --max-depth=1 | sort -h
Note that you don’t have to be in a directory to check its size. You can specify any directory like this :
du -h --max-depth=1 /path/to/directory
To only list, let’s say, the 10 biggest directories, you can use the du command along with the head command. We will also use the tail command to avoid listing the size of the current directory like this :
du -h --max-depth=1 2> /dev/null | sort -hr | tail -n +2 | head
We hope you were able to use this incorporate this command in your shell script and in your daily life to list all directories and sort them by size, you can also alias this long command and use the alias instead so that you don’t have to type out a long command every time you want to check the size of current subdirectories.