Size directory linux terminal

How do I determine the total size of a directory (folder) from the command line?

The -h flag on sort will consider «Human Readable» size values.

If want to avoid recursively listing all files and directories, you can supply the —max-depth parameter to limit how many items are displayed. Most commonly, —max-depth=1

du -h --max-depth=1 /path/to/directory 

I use du -sh or DOOSH as a way to remember it (NOTE: the command is the same, just the organization of commandline flags for memory purposes)

There is a useful option to du called the —apparent-size. It can be used to find the actual size of a file or directory (as opposed to its footprint on the disk) eg, a text file with just 4 characters will occupy about 6 bytes, but will still show up as taking up ~4K in a regular du -sh output. However, if you pass the —apparent-size option, the output will be 6. man du says: —apparent-size print apparent sizes, rather than disk usage; although the apparent size is usually smaller, it may be larger due to holes in (‘sparse’) files, internal fragmentation, indirect blocks

This works for OS X too! Thanks, I was really looking for a way to clear up files, both on my local machine, and my server, but automated methods seemed not to work. So, I ran du -hs * and went into the largest directory and found out which files were so large. This is such a good method, and the best part is you don’t have to install anything! Definitely deserved my upvote

@BandaMuhammadAlHelal I think there are two reasons: rounding ( du has somewhat peculiar rounding, showing no decimals if the value has more than one digit in the chosen unit), and the classical 1024 vs. 1000 prefix issue. du has an option -B (or —block-size ) to change the units in which it displays values, or you could use -b instead of -h to get the «raw» value in bytes.

Источник

How to Find the Total Size of a Directory in Linux

For Linux users and administrators in a server-like environment, knowing the exact size of a directory tree through the system terminal is important. It will help you compare file directory properties and determine their storage allocation when you want to copy or move these directories to a different location.

du Command Examples

The command du is an abbreviation for disk usage. This command is case-sensitive. Be specific in the use of uppercase and lowercase naming conventions while referencing directory names.

Читайте также:  Форматирование раздела для linux

Let us look at the various ways of implementing the du command to list directory sizes in Linux.

1. Listing Current Directory Size

Navigate to the directory you are interested in and key in the “du” command.

Find Directory Size in Linux

The default usage of the “du” command without other command arguments or options inside a targeted directory can be broken down into two parts.

  1. It lists the sizes of the sub-directories inside the main directory. From the above example screenshot, “LinuxShellTips” is the main directory while “screenshots” and “August” are its sub-directories. The size of each sub-directory is listed in kilobytes (kb).
  2. It lists the size of the main directory housing other sub-directories as the last command line output entry. From the above example case, the main directory “LinuxShellTips” has a total size of 12576 kb.

2. Listing Specific Directory Sizes

If you are inside one director and you want to know the size of a particular sub-directory, implement your du command in the following manner:

Find Particular Directory Size in Linux

If you are after multiple directory sizes, you can also list them:

Find Multiple Directory Sizes in Linux

The file directory sizes in your home directory can be achieved in the following manner:

$ du ~/Downloads/ ~/Documents/ ~/Desktop/

Find Home Directory Sizes in Linux

It will list all other associated sub-directories to their root level.

3. Listing Directory Sizes in Human-Readable Format

In the above-covered examples, the directory sizes were listed in kilobytes format. To get an output in a human-readable format, implement the du command with the «-h» tag as a command argument:

Find Directory Size in Human-Readable Format

4. Listing Directory Sizes in Specified Formats

You can specify whether you want the targeted directory size display to be in kilobytes (k) or megabytes (m).

Find Directory Size in Format

5. Listing a Directory Total Size

The du command is implemented by combining it with the «-s» and «-h» flags. In this case, the grand total size of the “LinuxShellTips” directory is 13M or 13 megabytes.

For the combined grand total of targeted multiple directories, use the following command:

$ du -sh Documents/ Downloads/ Desktop/

The below command lists the sub-directory sizes of the targeted directories and sums them up to a final value.

$ du -ch Documents/ Downloads/ Desktop/

List Total Size of Directory

You can also combine the du command with the grep command, to sum up, a directory’s total size.

$ du -ch Documents/ | grep total

Find Total Size of Directory

6. N-th Level Listing of Directory and Sub-Directory Sizes

This option is recommended for a Linux system with a large and deep-rooted directory tree structure. You might want to know the combined size of specific directories from N levels deep.

Limit Depth of Directory Listing with Sizes

The «—max-depth» parameter specifies the depth you want to reach from the current directory structure. It could be 1, 2, 3, etc.

7. Listing and Sorting Directories Based on Size

This command helps you know the disk size usage of a parent working directory (pwd) directory from a specified sub-directory level. It sorts them by size.

Listing and Sorting Directory Sizes

8. Listing Directory and File Sizes

If you want your directory sizes list to be associated with directory files, include the «-a» flag in your du command.

Listing Directory and File Sizes

9. Listing Directory Sizes by Excluding File Types

Maybe you don’t want your listed directory size to account for any file with an extension like “.mp4”. You could implement this du command in the following manner from your parent working directory.

$ du -ch --exclude='*.mp4' | grep total

Listing Directory Sizes By Excluding File Types

This tutorial has made listing directory and sub-directory sizes in a Linux environment is a non-issue. You now know more than one way to achieve this objective. For more references to the du command, key in man du on your Linux terminal.

Читайте также:  Astra linux открыть порт 443

Источник

Check Directory Size in Linux

It is quite easy to check the size of directories and files using GUI. Getting the size of a directory using the command line can be much more difficult than when using GUI. With the ‘ls’ command, you can list the contents of a directory but you cannot see the exact space or directory size. Instead, you must explore more commands to get the exact size of the directory or file.

In this article, you will learn how to check directory size on Linux using the command line environment. All the commands demonstrated in this article were run on an Ubuntu 20.04 system. All methods and steps are performed in the terminal. You can quickly open the terminal window by typing Ctrl + Alt + t.

Following are some methods you may use to check directory size on Linux systems. We will explore these methods one by one:

Method 1: Check Directory Size Using du Command

The default command used to check the size of the directory is known as the ‘du’ command, which stands for disk usage. The du command is installed on most Linux distributions. Using the du command, you can view the current directory size of your system, as follows:

The above command displays a list of the home directory contents. The numbers displayed to the left show the sizes, in kilobytes, of each object.

Using the -h option, you can also display the output in more descriptive form, as follows:

The above command displays the space in the kilo, mega, and Gigabytes with numbers.

To find the size of the specific directory, use the following syntax:

You will need to run the above command as the sudo user, because some directories require certain permissions access particular directory content.

Use the following command to check the directory size of the /var directory:

With the -hc option, you can display the size of the specific directory in human-readable form, as follows:

You can also change the subdirectory path depth using the max-depth option. For example, if you only wanted to display the top directory, then you would need to set the max-depth=0, as follows:

Similarly, to retrieve the top directory with one layer of subdirectory, then you will set max-depth=1.

If you want to explore more commands related to du, then you can use the following command:

Method 2: Check Directory Size Using tree Command

The tree command is used to display directories, subdirectories, and files in the tree format. You can make this command more useful by inputting flags and options for customization. The tree command does not come already installed on most of the Linux systems. You can install this command using the apt package manager, as follows:

To display the current directory, subdirectories and files use the following command on the terminal:

With the tree command, you may also retrieve the content of a specific directory using the following syntax:

To list the content of /var directory, you will use the following command:

Читайте также:  Linux file permissions all users

After completing the command, it will display the total number of directories and subdirectories.

To learn more about the tree command, use the following command:

Method 3: Check Directory Size Using ncdu Command

The NCurses Disk Usage, abbreviated ‘ncdu,’ is also used to check the directory size. ncdu is not installed by default on most Linux systems. You will need to install this command using the command line through the apt package manager, as follows:

Using ncdu, you can view an interactive display of your system disk usage. Execute the following to try out this command:

The upper top left corner displays the current directory being viewed. The left column displays directory size in the numerical value, where the # signs indicate the size next to each directory. Using the arrow keys, you can navigate between these lines. Here, the purpose of the right arrow is to browse the directory, and the purpose of the left arrow is to move you back.

With the ncdu command, you may also target a particular directory, as follows:

To quit the ncdu interface, press ‘q,’ and for help, press ‘?’.

In this article, you learned how to check directory size of using the terminal command line on Ubuntu 20.04 Linux systems through three different methods. You may explore more commands related to the tree, ncdu, and du commands using the terminal. These commands can be used on all Linux distributions. If you have any questions or suggestions, feel free to comment below.

About the author

Karim Buzdar

Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. He blogs at LinuxWays.

Источник

Как посмотреть размер папки в Linux

Посмотреть занимаемое место конкретной директории на диске Linux получится через любой файловый менеджер. Достаточно открыть свойства файла. Но там информация отображается в кратком виде, а нередко нужны подробности. С помощью утилиты ls получить детальные сведения не получится. А вот утилита du для этих целей подойдет отлично.

В данной статье мы расскажем, как посмотреть размер папки в Linux с помощью du. Для этого разберем два примера ее использования.

Как посмотреть размер папки в Linux

Сначала мы опишем, как получить информацию об определенной папке, с учетом или без учета ее вложений. А потом перейдем к подпапкам в конкретном каталоге. Заодно упомянем несколько полезных нюансов работы с du, например, возможность сортировки данных.

1. Определённая папка

В качестве примера возьмем папку Downloads. Команда для вывода ее размера выглядит следующим образом:

sudo du -sh /home/root-user/Downloads

В результате выведется её занимаемое место на диске:

Второй полезный сценарий использования утилиты du заключается в выводе размера всех вложенных папок в определенной директории, без учета файлов внутри. Опять в качестве примера возьмем директорию Downloads. Вот нужная нам команда:

sudo du -h /home/root-user/Downloads

wBQrZNUcmqcUQAAAABJRU5ErkJggg= https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3031391294356171

Выводы

В статье мы вкратце рассказали о том, как посмотреть размер папки в Linux и ее вложений с помощью утилиты du. Заодно упомянули возможность сортировки и другие важные нюансы. А если вам интересны еще сценарии использования du в терминале Linux, то ознакомьтесь с данной статьей. Там подробно разобран ее синтаксис, доступные опции и конкретные примеры.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Оцените статью
Adblock
detector