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

问题描述 投票:0回答:1

我想在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"
bash shell comparison backup
1个回答
1
投票

-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
© www.soinside.com 2019 - 2024. All rights reserved.