Reputation: 1039
I'm writing a small bash script to use with cron, to backup the database. When I search for old backups (oder than 180 days), the find command shall delete them.
It does delete them, but both when it does and when there is nothing to delete, it returns 0.
#!/bin/bash
# Vars
TODAY=$(date +%d%m%y)
BDIR=/backup/
FLOG="/var/log/mydb_backup.log"
# Backing up the db
su -c "pg_dump --format=c --file=${BDIR}mydb_db_backup.${TODAY} mydb" postgres
if [ $? -eq 0 ]; then
LOG="mydb DB of ${TODAY} backed up!"
else
LOG="Problem to back up mydb DB of ${TODAY}"
fi
# Delete db backup older than 180+ days
find ${BDIR} -type f -mtime +180 -delete
if [ $? -eq 0 ]; then
LOG+=" - Old DB backup deleted"
else
LOG+=" - No Old DB backup to delete"
fi
# Writing result
echo ${LOG} >> ${FLOG}
echo $?
always return 0, even though it did not delete anything (should happen the first months only).
Is there something I am doing wrong?
Upvotes: 0
Views: 294
Reputation: 1039
Alright.. this is the best solution I can think of at the moment:
# Delete db backup older than 180+ days
find ${BDIR} -maxdepth 1 -type f -mtime +180 -printf "%f\n" > $FDEL
if [[ $? -eq 0 && $(wc -l <"$FDEL") -gt 0 ]]; then
cd $BDIR
xargs -d '\n' -a $FDEL rm
LOG+=" - Old DB backup deleted"
else
LOG+=" - No Old DB backup to delete"
fi
rm $FDEL
I print the result(s) to a file, I move to the backup folder and delete each of the file found in the list. The file created must be bigger than 0 Bytes, this means it is not empty and should delete what's inside.
Upvotes: 1