- Узнаем размер папки в Linux
- Способы определения размера папки
- Способ 1: Терминал
- Способ 2: Файловый менеджер
- Заключение
- How to find the size of a directory in Linux
- Method-1: Get the size of a directory in Linux with du command
- Method-2: Find the size of a directory in Linux with ncdu command
- Method-3: Check a directory size in Linux with tree command
- Conclusion
- How to Get the Size of a Directory in Linux
- Option 1: Display the Size of a Directory Using the du Command
- Option 2: Get Size of Directory in Linux Using tree Command
- Option 3: Find the Size of a Linux Directory Using ncdu Command
Узнаем размер папки в Linux
Зная о системе максимум информации, пользователь сможет легче определять все нюансы в ее работе. Немаловажным является знание сведений о размере папок в Linux, но для начала нужно определиться, каким способом для получения этих данных пользоваться.
Способы определения размера папки
Пользователи операционных систем на базе Linux знают, что большинство действий в них решаются несколькими способами. Так и в случае с определением размера папки. Такая, на первый взгляд, тривиальная задача может ввести в ступор «новичка», но инструкция, которая будет приведена ниже, поможет во всем детально разобраться.
Способ 1: Терминал
Чтобы получить подробнейшую информацию о размере папок в Linux, лучше воспользоваться командой du в «Терминале». Хотя данный способ может отпугнуть неопытного пользователя, который только перешел на Linux, он отлично подойдет для выяснения нужной информации.
Синтаксис
Вся структура утилиты du выглядит следующим образом:
du
du название_папки
du [опция] название_папки
Как видно, синтаксис у нее может строиться по-разному. Например, при выполнении команды du (без указания папки и опции) вы получите стену текста с перечислением размеров всех папок в текущей директории, что крайне неудобно для восприятия.
Лучше использовать опции, если вы хотите получить структурированные данные, подробнее о чем будет рассказано ниже.
Опции
Перед демонстрацией наглядных примеров команды du стоит перечислить ее опции, чтобы использовать все возможности при сборе информации о размере папок.
- -а — вывести на экран сведения о суммарном размере файлов, помещенных в каталог (в конце списка указывается суммарный объем всех файлов в папке).
- —apparent-size — показать достоверный объем помещенных внутрь каталогов файлов. Параметры некоторых файлов в папке иногда бывают недействительными, на это влияет множество факторов, так что использование этой опции помогает удостовериться в корректности данных.
- -B, —block-size=РАЗМЕР — перевести полученные результаты в килобайты (K), мегабайты (M), гигабайты (G), терабайты (T). Например, команда с опцией -BM выведет размер папок в мегабайтах. Обратите внимание, что при использовании различных величин их значение имеет погрешность, ввиду округления до меньшего целого числа.
- -b — отображать данные в байтах (равнозначно —apparent-size и —block-size=1).
- -с — показывать общий итог подсчета размера папки.
- -D — приказ проследовать лишь по тем ссылкам, которые указаны в консоли.
- —files0-from=ФАЙЛ — показать отчет по использованию диска, чье имя будет введено вами в графу «ФАЙЛ».
- -H — равнозначен ключу -D.
- -h — перевести все значения в понятный для человека формат, используя соответствующие единицы измерения данных (килобайты, мегабайты, гигабайты и терабайты).
- —si — практически равносильна прошлой опции, за исключением того, что использует делитель, равный одной тысяче.
- -k — отображать данные в килобайтах (то же самое, что и команда —block-size=1000).
- -l — приказ приплюсовывать все данные в том случае, когда есть боле одной сноски на один и тот же объект.
- -m — отображать данные в мегабайтах (аналогично команде —block-size-1000000).
- -L — строго следовать указанным символьным ссылкам.
- -P — аннулирует предыдущую опцию.
- -0 — каждую выводимую строчку информации заканчивать нулевым байтом, а не начинать новую строку.
- -S — при подсчете занятого пространства не учитывать размер самих папок.
- -s — показывать размер лишь той папки, которую вы указали в качестве аргумента.
- -x — не выходить за пределы указанной файловой системы.
- —exclude=ОБРАЗЕЦ — игнорировать все файлы, совпадающие с «Образцом».
- -d — задать глубину следования папкам.
- —time — показать сведения о последних изменениях в файлах.
- —version — уточнить версию утилиты du.
Теперь, зная все опции команды du, вы сможете самостоятельно применять их на практике, осуществляя гибкую настройку сбора информации.
Примеры использования
Напоследок, чтобы закрепить полученную информацию, стоит рассмотреть несколько примеров использования команды du.
Без ввода дополнительных опций утилита будет автоматически выводить имена и размер папок, расположенных по указанному пути, попутно выводя также и подпапки.
Для вывода данных об интересующей вас папке введите ее имя в контекст команды. К примеру:
du /home/user/Загрузки
du /home/user/Изображения
Чтобы было проще воспринимать всю выводимую информацию, воспользуйтесь опцией -h. Она подстроит размер всех папок под общепринятые единицы измерения цифровых данных.
du -h /home/user/Загрузки
du -h /home/user/Изображения
Для полного отчета об объеме, занимаемом определенной папкой, укажите вместе с командой du опцию -s, а после — имя интересующей вас папки.
du -s /home/user/Загрузки
du -s /home/user/Изображения
Но удобнее будет задействовать опции -h и -s вместе.
du -hs /home/user/Загрузки
du -hs /home/user/Изображения
Опция -с применяется для вывода общей суммы, занимаемого папками места (ее можно применить вместе с опциями -h и -s).
du -chs /home/user/Загрузки
du -chs /home/user/Изображения
Еще одна крайне полезная «фишка», о которой не было сказано выше, — это опция —-max-depth. С помощью нее вы сможете задать глубину, с которой утилита du будет следовать папкам. Например, при указанном коэффициенте глубины в одну единицу, будут просмотрены данные о размере всех без исключения папок, указанных в данном отрезке, а папки в них будут проигнорированы.
Выше были приведены самые популярные применения утилиты du. Используя их, вы сможете добиться желаемого результата — узнать размер папки. Если же опций, используемых в примерах, вам покажется мало, то можете самостоятельно разобраться с остальными, применяя их на практике.
Способ 2: Файловый менеджер
Безусловно, «Терминал» способен предоставить просто кладезь информации о размере папок, но рядовому пользователю будет сложно в нем разобраться. Куда привычней наблюдать графический интерфейс, нежели набор символов на темном фоне. В этом случае, если нужно узнать лишь размер одной папки, лучшим вариантом будет воспользоваться файловым менеджером, который установлен в Linux по умолчанию.
Примечание: в статье будет использован файловый менеджер Nautilus, который является стандартным для Ubuntu, однако инструкция будет применима и к другим менеджерам, отличаться может лишь расположение некоторых элементов интерфейса и их отображение.
Чтобы узнать размер папки в Linux с помощью файлового менеджера, выполните следующие действия:
- Откройте менеджер файлов, нажав по иконке на панели задач или проведя поиск по системе.
После проделанных манипуляций перед вами появится окно, в котором нужно отыскать строку «Содержание» (1), напротив нее и будет указан размер папки. Кстати, чуть ниже будет находиться информация об оставшемся свободном месте на диске (2).
Заключение
По итогу вы имеете два способа, с помощью которых можно узнать размер папки в операционных системах на базе Linux. Хоть они и предоставляют одну и туже информацию, варианты ее получения кардинально отличаются. Если вам надо быстро узнать размер одной папки, то идеальным решением будет использование файлового менеджера, а если вам нужно получить как можно больше информации, то отлично подойдет «Терминал» с утилитой du и ее опциями.
Помимо этой статьи, на сайте еще 12315 инструкций.
Добавьте сайт Lumpics.ru в закладки (CTRL+D) и мы точно еще пригодимся вам.
Отблагодарите автора, поделитесь статьей в социальных сетях.
Источник
How to find the size of a directory in Linux
It is very easy to check the size of directories and files in Linux using the GUI, but it is not always easy to get the size of a directory using the command line.
The ls command can be used to list the contents of a directory, but it does not display the exact directory size and always shows each directory size as 4096 bytes (4 KB), which is the size of space on the disk that is used to store the meta-information for the directory, not what it contains
You can get the actual size of a directory using the du command (Disk Usage), which is widely used by Linux administrators, but you can explore other commands for this purpose. Let’s explore them.
This guide shows you how to find the directory size in Linux using the below three commands:
- du command
- ncdu command
- tree command
Method-1: Get the size of a directory in Linux with du command
The du command refers to disk usage. It is a standard Unix program that is used to estimate disk space usage in the present working directory when no path is specified.
It recursively summarizes the disk usage to obtain a directory and its sub-directory sizes.
Use the below du command format to get the total size of each directory, including sub-directories.
The above command will print the size of each file and the actual size of each directory, including their sub-directory as well as the total size.
Details:
- du: It’s a command
- -h: Print sizes in human readable format (e.g., 1K, 234M, 2G)
- -c: Produce a grand total
- /home/daygeek/Documents/: The path of directory
- sort -rh: Sort the results with numerical value
- head -20: Output the first 20 lines result
Use the following du command format to get the total size of a specific directory:
If you want to find out the size of the first-level sub-directories, including their sub-directories, for a given directory on Linux, use the following du command format:
Method-2: Find the size of a directory in Linux with ncdu command
The ncdu (NCurses Disk Usage) is a curses-based version of the well-known ‘du’ command, and provides a fast way to see which directories are consuming your disk space.
The ncdu command scans the given directory and displays their files and folder sizes recursively as shown below:
Method-3: Check a directory size in Linux with tree command
The pstree command displays directory contents recursively in a tree-like format, which is very convenient way to display the directory hierarchy and that improves the readability of the output.
As you can see, the tree command output is straight forward compared to the du & ncdu commands.
Conclusion
You have learnt the three different commands to find the size of a directory in Linux.
If you have questions, feel free to leave a comment below, and we will get back to you as soon as we can. Happy learning!
Источник
How to Get the Size of a Directory in Linux
Home » SysAdmin » How to Get the Size of a Directory in Linux
Many users run Linux from the command line. However, the command line — sometimes known as the terminal — doesn’t have an intuitive interface for checking disk space in Linux.
This guide shows you how to find the size of a specific directory in Linux from the command line.
- A system running Linux
- A command line / terminal window (available by clicking Search, then typing terminal)
- A user account with sudo or root privileges
Note: In Linux, a directory is the equivalent of a folder in Windows. A directory may have directories inside (called subdirectories), or it may only contain files.
Option 1: Display the Size of a Directory Using the du Command
The du command stands for disk usage. This command is included by default in most Linux distributions.
You can display the size of your current directory by typing du in the command line:
The system should display a list of the contents of your home directory, with a number to the left. That number is the size of the object in kilobytes.
You can add the -h option to make the output more readable:
Each entry will start with a number and a letter. The number is the amount of space used, and the letter (usually K, M, or G) indicates Kilobytes, Megabytes, or Gigabytes. For example:
To find the size of a specific directory different from your current working directory. The du command allows you to specify a directory to examine:
This displays the size of the contents of the /var directory. You may see some entries with an error, as in the image below.
This happens when your user account does not have permission to access a particular directory. Use the sudo or su command to get access privileges:
Note: Some versions of Linux don’t enable sudo by default. You can use the su command to switch to the root user account instead.
To display total disk usage of a particular directory, use the -c command:
Options can be combined. If you wanted to repeat the previous command in human-readable format, enter the following:
You can limit the scan to a certain level of subdirectory by using the max-depth option. For example, to scan only the size of the top directory, use —max-depth=0 :
If you wanted to list only the top directory and the first layer of subdirectories, change —max-depth=1 :
If you run into trouble or want to explore more options for the du command, enter the following command to display the help file:
Option 2: Get Size of Directory in Linux Using tree Command
By default, the tree command is not included in some versions of Linux. To install it, enter the following:
- For Debian / Ubuntu
- For CentOS / RedHat
The tree command displays a visual representation of your directories. It uses lines to indicate which subdirectories belong where, and it uses colors to indicate directories and files.
tree can also be used with options. To display a human-readable size of the current directory’s subdirectories, enter the following:
Like the du command, tree can target a specific directory:
This command takes a few moments since the /var directory has many entries.
The tree command also has a help file, which you can access by entering:
Option 3: Find the Size of a Linux Directory Using ncdu Command
The ncdu tool stands for NCurses Disk Usage. Like the tree command, it is not installed by default on some versions of Linux. To install it, enter the following:
- For Debian / Ubuntu
- For CentOS / RedHat
The ncdu utility is an interactive display of your disk usage. For example, enter the following:
In the upper left corner, it displays the current directory being scanned. A column on the left displays the numerical size, a graph of #- signs to indicate the relative size, and the file or directory.
Use the up and down arrows to select different lines. The right arrow will browse into a directory, and the left arrow will take you back.
ncdu can be used to target a specific directory, for example:
For help, press the ? key inside the ncdu interface. To quit, press the letter q .
Note: Learn how to move directories in Linux using the GUI or system commands.
You now have three different options to find the size of a directory in Linux operating systems.
If you want to learn more about directories in Linux, read our article how to rename directories in Linux.
Источник