arkcza
arkcza

Reputation: 13

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

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"

Upvotes: 1

Views: 3963

Answers (1)

JRFerguson
JRFerguson

Reputation: 7516

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

Upvotes: 2

Related Questions