Обновил скрипт для резервного копирования. Убрал вызов bc
, вынес всё в отдельные функции, причесал код, чтобы ShellCheck был счастлив:
#!/usr/local/bin/bash
BACKUP_ROOT=/var/backups/manual/
BACKUP_DIR="$BACKUP_ROOT"$(date +"%Y-%m-%d/%H-%M")
PREFIX=$(date +"%Y%m%d_%H%M")
LIMIT=$((4*1024*1024))
exit_on_error() {
exit_code=$?
if [ $exit_code -ne 0 ]; then
>&2 echo -e "FAIL"
exit $exit_code
fi
}
print_used_space() {
printf "Used space: "
SIZE=$(du -sB 1 $BACKUP_ROOT | cut -f 1)
printf "%sMb(%s%%)\n" "$((SIZE / 1024))" "$((SIZE * 100 / LIMIT))"
}
backup_etc() {
FILENAME="$PREFIX"_etc.tar.bz2
printf "Creating %s .. " "$FILENAME"
if /usr/bin/tar -Pjcf "$BACKUP_DIR"/"$FILENAME" /etc /usr/local/etc /home /var/db/ports /var/named/etc/namedb /root/scripts > /dev/null 2>&1; then
printf "OK\n"
else
exit_on_error
fi
}
backup_site() {
FILENAME="$PREFIX"_www.tar.bz2
printf "Creating %s .. " "$FILENAME"
if /usr/bin/tar -Pjcf "$BACKUP_DIR"/"$FILENAME" /usr/local/www > /dev/null; then
printf "OK\n"
else
exit_on_error
fi
}
backup_db() {
FILENAME="$PREFIX"_db.sql.bz2
printf "Creating %s .. " "$FILENAME"
if /usr/local/bin/mysqldump --login-path=backup --opt --all-databases --triggers --routines --events | bzip2 -c > "$BACKUP_DIR"/"$FILENAME"; then
printf "OK\n"
else
exit_on_error
fi
}
remove_old_files() {
removed=0
for days in $(seq 100 -1 0)
do
SIZE=$(du -sB 1 $BACKUP_ROOT | cut -f 1)
if [[ $SIZE -le $LIMIT ]]; then
break
fi
if [[ -z "$(find $BACKUP_ROOT -type f -mtime +"$days")" ]]; then
continue
fi
printf "Removing files older than %d days:\n" "$days"
find $BACKUP_ROOT -type f -mtime +"$days"d -delete -print
find $BACKUP_ROOT -empty -type d -delete -print
removed=1
done
if [ $removed -ne 0 ]; then
true
return
fi
false
}
if [ ! -d "$BACKUP_DIR" ]; then
mkdir -p "$BACKUP_DIR"
fi
backup_etc
backup_site
backup_db
print_used_space
remove_old_files && print_used_space
true
Bash