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 can I calculate the size of a directory?
The -s option means that it won’t list the size for each subdirectory, only the total size.
Actually du ‘s default unit is 512-byte blocks according to POSIX, and kilobytes on Linux (unless the environment variable POSIXLY_CORRECT is set) or with du -k .
if the directory is very big and have lots of subdirectories, it takes lots of time. almost 1 min.. is that normal? is there a way to get the size more rapidly?
While using a separate package such as ncdu may work well, the same comparison of many folders can be done, to some degree, by just giving du a list of folders to size up. For example to compare top-level directories on your system.
will list in human-readable format the sizes of all the directories, e.g.
656K ./rubberband 2.2M ./lame 652K ./pkg-config
See the man page and the info page for more help:
-b , —bytes is equivalent to —apparent-size —block-size=1
The -c doesn’t make sense to use together with -s , right? -s only displays the size of the specified directory, that is the total size of the directory.
du -ahd 1 | sort -h will have a better visualization that sorted the items.
$ du -ahd 1 | sort -h 2.1M ./jinxing.oxps 2.1M ./jx.xps 3.5M ./instances_train2014_num10.json 5.9M ./realsense 7.8M ./html_ppt 8.5M ./pytorch-segmentation-toolbox 24M ./bpycv 24M ./inventory-v4 26M ./gittry 65M ./inventory 291M ./librealsense 466M .
ls -ldh /etc drwxr-xr-x 145 root root 12K 2012-06-02 11:44 /etc
-l is for long listing ; -d is for displaying dir info, not the content of the dir, -h is for displaying size in huma readable format.
This isn’t correct, the person asking is clearly looking for footprint of a directory and it’s contents on disk. @sepp2k’s answer is correct.
The ls -ldh command only shows the size of inode structure of a directory. The metric is a reflection of size of the index table of file names, but not the actual size of the file content within the directory.
du -hax --max-depth=1 / | grep '2G' | sort -nr
This helps find large directories to then sift through using du -sh ./*
You can use «file-size.sh» from the awk Velour library:
This gives a more accurate count than du. Unpack a tarball on two servers and use «du -s» (with or without —bytes) and you will likely see different totals, but using this technique the totals will match.
The original question asked the size, but did not specify if it was the size on disk or the actual size of data.
I have found that the calculation of ‘du’ can vary between servers with the same size partition using the same file system. If file system characteristics differ this makes sense, but otherwise I can’t figure why. The ‘ls|awk» answer that Steven Penny gave yields a more consistent answer, but still gave me inconsistent results with very large file lists.
Using ‘find’ gave consistent results for 300,000+ files, even when comparing one server using XFS and another using EXT4. So if you want to know the total bytes of data in all files then I suggest this is a good way to get it:
find /whatever/path -type f -printf "%s\n"|awk ' END '