- How do I determine the total size of a directory (folder) from the command line?
- Как посмотреть размер папки в Linux
- Как посмотреть размер папки в Linux
- 1. Определённая папка
- Выводы
- Check folder size in Bash
- 8 Answers 8
- How to Check Directory Size in Ubuntu Command Line
- Use the du command to check directory size in Ubuntu
- Use the tree command to check directory size in Ubuntu
- Use the ncdu utility to check directory size in Ubuntu
- Use the dust utility to check directory size in Ubuntu
- Final Words
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.
Как посмотреть размер папки в 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
Выводы
В статье мы вкратце рассказали о том, как посмотреть размер папки в Linux и ее вложений с помощью утилиты du. Заодно упомянули возможность сортировки и другие важные нюансы. А если вам интересны еще сценарии использования du в терминале Linux, то ознакомьтесь с данной статьей. Там подробно разобран ее синтаксис, доступные опции и конкретные примеры.
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
Check folder size in Bash
I’m trying to write a script that will calculate a directory size and if the size is less than 10GB, and greater then 2GB do some action. Where do I need to mention my folder name?
# 10GB SIZE="1074747474" # check the current size CHECK="`du /data/sflow_log/`" if [ "$CHECK" -gt "$SIZE" ]; then echo "DONE" fi
Since this is a popular question — If any beginner is encountering the answers on this question and wants to learn more about what the heck du is and how everyone knows all these commands: You can type man du in your terminal to lookup the du command in the manual. This will display an output which you can view, and will summarize all the flags like -h, -c, -s, -b, -B, —apparent-size, etc. that answers are you suggesting you use. Then, you can decide for yourself how you best want to use du for your specific use case.
8 Answers 8
which will give you a brief output of the size of your target directory. Using a wildcard like * can select multiple directories.
If you want a full listing of sizes for all files and sub-directories inside your target, you can do:
- Add the argument -c to see a Total line at the end. Example: du -hcs or du -hc .
- Remove the argument -h to see the sizes in exact KiB instead of human-readable MiB or GiB formats. Example: du -s or du -cs .
With no directory path specified it will default to the current working directory. so du -hs == du -hs . .
if you just want to see the folder size and not the sub-folders, you can use:
You should know that du shows the used disk space; and not the file size.
You can use —apparent-size if u want to see sum of actual file sizes.
--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, and the like
And of course theres no need for -h (Human readable) option inside a script.
Instead You can use -b for easier comparison inside script.
But You should Note that -b applies —apparent-size by itself. And it might not be what you need.
-b, --bytes equivalent to '--apparent-size --block-size=1'
so I think, you should use —block-size or -B
#!/bin/bash SIZE=$(du -B 1 /path/to/directory | cut -f 1 -d " ") # 2GB = 2147483648 bytes # 10GB = 10737418240 bytes if [[ $SIZE -gt 2147483648 && $SIZE -lt 10737418240 ]]; then echo 'Condition returned True' fi
How to Check Directory Size in Ubuntu Command Line
The ls command shows the file size in human-readable format with ls -lh. However, the directory size is always displayed as 4k.
I’ll explain the logic behind 4k directory size later. For now, the bigger question is how do you get the directory size in Ubuntu terminal?
Like most things in Linux, there are several ways to do it. Let’s start with the ‘official’ command for checking the size of a directory.
Use the du command to check directory size in Ubuntu
The du (disk usage) command is a popular solution for checking directory sizes in Linux.
du [option] path_to_file_or_directory
For example, I will be getting details of Directory and use -h option to get output in human-readable form:
But how could a directory containing one sub-directory worth 1.6 Gb can sum around 16 gigs? Because by default, it only shows details of sub-directories.
And by using -a option, you can include files, making it a more sensible output:
Now, you can have a better idea of how it was sized around 16 gigs!
But the du command has a lot more to offer and if you want to utilize it to its max potential, I’d recommend checking out our detailed guide:
Use the tree command to check directory size in Ubuntu
You will find me using the tree command in various guides to show the file system in a hierarchy but it can also be used to get directory size.
By using —du with the tree command, it will get you the total size of a directory including the size of every file and sub-directory present inside.
And if you’re curious why I used the -h option here, it is for getting output in the human-readable form!
Use the ncdu utility to check directory size in Ubuntu
Built on top of du (which I discussed earlier), the ncdu is an interactive and efficient way of checking disk space.
But it requires manual installation and can be done through the given command:
Now, you just have to append the directory with the ncdu command:
Use the dust utility to check directory size in Ubuntu
You can think of dust as an enhanced version of tree utility that is specifically made for checking disk space.
It has a fascinating way of presenting data with graph and shows how many percent of the total size is occupied by a single file!
But you’d need to use the cargo package manager for installation and to set up cargo in Ubuntu, you can check out our detailed guide:
And here are quick 3 commands to install and setup cargo:
sudo apt install curl curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source $HOME/.cargo/env
Once you are done with the setup, you can install dust by the given command:
Now pair the name of the directory with the dust command:
Final Words
Through this guide, I explained multiple ways of checking directory size and the last two were my favorite ones as they went with a different approach.
Now coming back to the mystery of the 4K directory size the ls command shows. You know, a directory is simply a special file that has the details of where the files (inside the directory) are stored in the memory. The 4K is the block size of the system, and every file has this minimum block size.
And if you have any queries, make sure to leave a comment and I’ll be there with answers.