【问题标题】:How to check if the size of a file or a directory is larger than a value in Bash?如何检查文件或目录的大小是否大于 Bash 中的值?
【发布时间】:2019-08-24 23:12:52
【问题描述】:

我想在 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】:

-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

【讨论】:

  • 是的,但这会将所有子目录的大小汇总为一个,但我想检查它们各自的大小,例如,如果其中一个超过 10 mb,而我的限制是 12 mb,则省略该目录。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-24
  • 1970-01-01
  • 2013-05-15
  • 1970-01-01
相关资源
最近更新 更多