检查Bash中的文件夹大小

我试图编写一个脚本来计算目录大小,如果大小小于10GB,大于2GB则执行一些操作。 我需要在哪里提及我的文件夹名称?

# 10GB SIZE="1074747474" # check the current size CHECK="`du /data/sflow_log/`" if [ "$CHECK" -gt "$SIZE" ]; then echo "DONE" fi 

你可以做:

 du -h your_directory 

这会给你目标目录的大小。

如果你想要一个简短的输出,你可以du -hcs your_directory

如果您只想查看文件夹大小而不是子文件夹,则可以使用:

 du -hs /path/to/directory 

更新:

你应该知道du显示使用的磁盘空间; 而不是文件大小。

如果你想看到实际文件大小的总和,你可以使用--apparent-size

 --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 

当然,脚本中不需要-h (人类可读)选项。

相反,您可以使用-b来更轻松地在脚本内进行比较。

但是你应该注意到-b本身适用于--apparent-size 。 这可能不是你所需要的。

 -b, --bytes equivalent to '--apparent-size --block-size=1' 

所以我认为,你应该使用--block-size-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 

使用摘要( -s )和字节( -b )。 您可以削减摘要的第一个字段。 把它放在一起:

 CHECK=$(du -sb /data/sflow_log | cut -f1) 

为了获得目录的大小,仅此而已:

 du --max-depth=0 ./directory 

输出看起来像

 5234232 ./directory 

如果你只是想看到文件夹的聚合大小,可能是MB或GB格式,请尝试下面的脚本

 $du -s --block-size=M /path/to/your/directory/ 
 # 10GB SIZE="10" # check the current size CHECK="`du -hs /media/662499e1-b699-19ad-57b3-acb127aa5a2b/Aufnahmen`" CHECK=${CHECK%G*} echo "Current Foldersize: $CHECK GB" if (( $(echo "$CHECK > $SIZE" |bc -l) )); then echo "Folder is bigger than $SIZE GB" else echo "Folder is smaller than $SIZE GB" fi