Joom187
Joom187

Reputation: 305

Testing whether any files are older than 7 days

I have a script that finds files in a folder and deletes them if they are older than 7 days. However, I have a little issue.

#!/bin/bash
BACKUPDIR=/home/vagrant/script/aerospike_backups
TIMESTAMP=$(date +%Y-%m-%d)
LOGPATH=/tmp/logs.txt
[email protected]
[email protected]
#Let's check existing backups, and if it's older than 7 days delete
find_old () {
     if [ -z $(find $BACKUPDIR -mtime +7 -print ) ]
       then
            return 10
              else
find $BACKUPDIR -mtime +7 -delete && echo "Backups deleted at $HOSTNAME on $TIMESTAMP" >  $LOGPATH

fi
} 

And if I execute this script with empty $BACKUPDIR from terminal use ./scriptname, then type echo $? the shell outputs 10 code as expected because there's not files which is older 7 days or there's just no files at all.

But after I add more if condition like

if [[ $(find_old | echo $?) -gt 0 ]]
then
echo "Script return error code"
else
echo "all is ok"

The script gives me the output all is ok, but it really shouldn't? What's wrong?

Upvotes: 2

Views: 945

Answers (1)

codeforester
codeforester

Reputation: 42999

It's much better to store the found files in an array and then delete them, rather than calling find twice - that way, we are guaranteed to delete the exact set of files that we found, in addition to being much more efficient.

find_old() {
    while read -r -d '' file; do                  # read the output of find one file at a time
      files+=("$file")                            # append to the array
    done < <(find "$BACKUPDIR" -mtime +7 -print0) # generate NUL separated list of files
    if ((${#files[@]} == 0)); then
      # no files found
      return 10
    else
      printf '%s\0' "${files[@]}" | xargs -0 rm -f --
    fi
}

And then, call your function as:

find_old; exit_code=$?
if ((exit_code > 0)) {
  echo "Script returned error code $exit_code"
else
  echo "All is OK"
fi

I have fixed a few issues in your code:

  • it is important to quote your variables while expanding them. for example: find "$BACKUPDIR" instead of find $BACKUPDIR
  • if [[ $(find_old | echo $?) -gt 0 ]] is not the way to check the exit code of the function; you need to check $? directly

See also:

Upvotes: 6

Related Questions