Check folder size in Bash
You can do:
du -hs your_directory
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:
du -h your_directory
Tips:
Add the argument
-c
to see a Total line at the end. Example:du -hcs
ordu -hc
.Remove the argument
-h
to see the sizes in exact KiB instead of human-readable MiB or GiB formats. Example:du -s
ordu -cs
.
if you just want to see the folder size and not the sub-folders, you can use:
du -hs /path/to/directory
Update:
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