1

I want to write a short backup script in Bash that lets me choose a directory that I want to save, and then compress it. I've got that done.

Next, I wanted to make it so that I could compare the size of the files that are to be copied. I used du -b /example/directory | cut -f1 . That got me the sizes of folders in that directory, without their names. But I can't really compare it to a value using the if statement, because it isn't an integer statement.

This is my code so far.

#!/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"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
arkcza
  • 13
  • 1
  • 3

1 Answers1

2

Add the -s (summarize) option to your du. Without it, you are returning the sizes of every subdirectory which makes your final size comparison fail.

Change:

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

to:

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

If you want to test each individual object, do something like:

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
JRFerguson
  • 7,426
  • 2
  • 32
  • 36
  • Yes, but that would sum up the size of all subdirectories into one, but I want to check their individual sizes so if, for example, one of them is over 10 mb, and my limit is 12 mb, then that directory is omitted. – arkcza Apr 03 '19 at 12:47
  • @JRFerguson, can I use `-h` for `du`? For example, `if [ 1.4G -le 700M]`. – Oo'- Jul 25 '22 at 05:01