How To Get Size Of Directory In Linux

While managing your Linux system, one of the crucial tasks is keeping track of your disk space usage. It is essential to understand which directories take up most of the space. In this blog post, we’ll guide you through the process of determining the size of a directory in Linux and formatting the output as HTML.

Using the ‘du’ Command

The ‘du’ command, short for disk usage, is the standard tool in Linux for getting the size of a directory. Here is the basic syntax:

du -sh /path/to/directory

The -s option stands for ‘summarize’ and gives us the total size of the directory. The -h option stands for ‘human-readable’, which provides the size in a format that is easier to understand (e.g., K for kilobytes, M for megabytes, G for gigabytes).

Formatting the output as HTML

By default, the ‘du’ command outputs the size of the directory in the terminal. However, we can redirect this output into an HTML file. To do this, we will need to create a shell script. Below is a simple example:

#!/bin/bash
echo "

<title>Directory Size</title>


<pre>" &gt; directory_size.html
du -sh /path/to/directory &gt;&gt; directory_size.html
echo "</pre>

" &gt;&gt; directory_size.html

In this script, the echo command is used to write HTML tags into the ‘directory_size.html’ file. We use the ‘>>‘ operator to append the output of the ‘du’ command to the same file. This will create an HTML file that displays the size of the directory.

After saving this script (for example, as ‘dir_size.sh’), we need to make it executable by running the command:

chmod +x dir_size.sh

Then, we can run the script with:

./dir_size.sh

This will create a file named ‘directory_size.html’ in the same directory. Open it in a web browser, and you will see the size of the target directory displayed in a neat HTML format.

That’s it! You have successfully retrieved the size of a directory in Linux and formatted the output as an HTML document. Feel free to modify the script to adapt it to your specific needs.