如何检查文件或目录的大小是否大于Bash中的值?

How to check if the size of a file or a directory is larger than a value in Bash?

我想在 Bash 中写一个简短的备份脚本,让我选择一个我想保存的目录,然后压缩它。我已经完成了。

接下来,我想制作它,以便我可以比较要复制的文件的大小。我用了du -b /example/directory | cut -f1 。这让我得到了那个目录中文件夹的大小,没有它们的名字。但我无法真正将它与使用 if 语句的值进行比较,因为它不是整数语句。

到目前为止,这是我的代码。

#!/bin/bash
#Which folders to backup
backup_files="/home"

# Where to save
dest="/home/student"

# Check size of each folder
file_size=$(du -b /example/directory | cut -f1)

# Size limit
check_size=1000

# Archive name
day=$(date +%A)
hostname=$(hostname -s)
archive_file="$hostname-$day.tar.gz"

# Here's the problem I have
if [ "$file_size" -le "$check_size" ]; then
    tar -vczf /$dest/$archive_file $backup_files
fi

echo "Backup finished"

-s(汇总)选项添加到您的 du。没有它,您将返回每个子目录的大小,这会使您的最终大小比较失败。

变化:

file_size=$(du -b /example/directory | cut -f1)

至:

file_size=$(du -bs /example/directory | cut -f1)

如果您想测试每个单独的对象,请执行以下操作:

du -b /example/directory |
    while read size name
    do
        if [ "$size" -le "$limit" ]; then
            # do something...
        else
            # do something else - object too big...
        fi       
    done