0

Very new to bash as you will see in code below.

I want to get the file size in bytes of a file, compare that to a fixed value and send an email if the latter is too small.

Code:

#!/bin/bash
f=$(find /var/lib/xxxxxx/backups/xxxxxxxxDB*.gz -ctime 0 -print -exec ls -l {} \; | awk '{print $5}')

if [$f -lt 60000000000] ; then
echo "hello";
fi

The output of the command above is 18607414901 bytes, i.e. 18gb.

What I want is to execute command if that is less than 60gb. The echo command is used just to test that.

./backupsql.sh: line 4: [: missing `]'
  • 4
    Did you read the documentation for your find command (man find)? it likely has an option to identify files that are smaller than a given size directly. – steeldriver May 19 '17 at 15:08
  • 1
    another plug for shellcheck.net – Jeff Schaller May 19 '17 at 15:27
  • 1
    Apart from that, since the Q was tagged with [linux], you probably have GNU find, and can get the file size with find ... -printf "%s\n" (no need for external ls). Also, as steeldriver hinted, even POSIX find has -size to match based on the file size. – ilkkachu May 19 '17 at 21:59

3 Answers3

0

You need some spaces in the test:

if [ $f -lt 60000000000 ] ;then
    echo "Hello"
fi
NickD
  • 2,926
0

You may use wc command with -c option (print the byte counts) to get file size in bytes for further comparison:

#!/bin/bash

s=$(wc -c < /var/lib/xxxxxx/backups/xxxxxxxxDB*.gz)
if [ $s -lt 60000000000 ]; then
echo "hello"
fi

Another way is using stat command with -c option:

#!/bin/bash

s=$(stat -c "%s" /var/lib/xxxxxx/backups/xxxxxxxxDB*.gz)
if [ $s -lt 60000000000 ]; then
echo "hello"
fi

-c - tells to use the specified format

%s - the format representing total size, in bytes

0

Script? Here is a one-liner:

[ $(stat -c %s $(ls -tr /var/lib/xxxxxx/backups/xxxxxxxxDB*.gz | tail -n 1)) -lt 60000000000 ] && echo "Error" | mail -s "Too small" root@example.org

ls -tr /var/lib/xxxxxx/backups/xxxxxxxxDB*.gz will list all files in reverse order by timestamp. The last one is the newest. tail -n 1 will show the last file. $(..) is the text of a command. stat -c %s <file> will show the size of a file. [ ... ] is actually the command /usr/bin/test if return code is 0 it will run the command after &&.

If you run this command in crontab you have to escape % with \, like [ $(stat -c \%s ..

The script version:

#! /bin/bash
LASTFILE=$(ls -tr /var/lib/xxxxxx/backups/xxxxxxxxDB*.gz | tail -n 1)
if [ $(stat -c %s $LASTFILE) -lt 60000000000 ]; then
  echo "$LASTFILE" | mail -s "Too small" root@example.org
fi
hschou
  • 2,910
  • 13
  • 15