如何检查文件或目录的大小是否大于bash中的值?
我想在bash中编写一个简短的备份脚本,让我选择一个要保存的目录,然后压缩它。我已经做完了 接下来,我想做一个比较,以便比较要复制的文件的大小。我使用了如何检查文件或目录的大小是否大于bash中的值?,bash,shell,comparison,backup,Bash,Shell,Comparison,Backup,我想在bash中编写一个简短的备份脚本,让我选择一个要保存的目录,然后压缩它。我已经做完了 接下来,我想做一个比较,以便比较要复制的文件的大小。我使用了du-b/example/directory | cut-f1。这让我知道了该目录中文件夹的大小,没有它们的名称。但我无法将它与使用if语句的值进行比较,因为它不是整数语句 这是到目前为止我的代码 #!/bin/bash #Which folders to backup backup_files="/home" #Where to save d
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)
致:
如果要测试每个单独的对象,请执行以下操作:
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,则忽略该目录。
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