我的目标是每月将我的 ubuntu/home/
目录备份到外部驱动器,将其连接到计算机后,我就可以在 中看到它/media/ironman/Elements
。为此,我使用rsync
。
外部驱动器并不总是挂载的,所以我制作了一个交互式脚本,当驱动器没有挂载时,它会提示我挂载驱动器。我想安排这个脚本,anacron
因为我的笔记本电脑经常关机。我认为我的设置不起作用是因为交互式部分:当我从命令行运行脚本时,我自然可以在同一命令行中看到它的输出。但是,anacron 不是从命令行运行的。
这是脚本/home/ironman/scripts/backup_anacron.sh
#!/bin/bash
# Variables
SOURCE_DIR="/home/ironman"
TARGET_DIR="/media/ironman/Elements/backup_$(date +%Y%m%d)"
EXCLUDES="--exclude=\"lost+found\" --exclude=\".cache\""
RSYNC_CMD="rsync -a --info=progress2 $EXCLUDES $SOURCE_DIR/ $TARGET_DIR"
# Function to check if the drive is mounted
check_mount() {
if grep -qs "/media/ironman/Elements " /proc/mounts; then
echo "Backup drive is mounted."
return 0
else
return 1
fi
}
# Check whether backup drive has enough free space
check_space() {
# Get available space on target drive in kilobytes
available_space=$(df --output=avail "/media/ironman/Elements" | tail -1)
# Get required space for the source directory in kilobytes
required_space=$(du -sk "$SOURCE_DIR" | cut -f1)
if [ "$available_space" -ge "$required_space" ]; then
echo "Enough space on backup drive. Required: $required_space KB, Available: $available_space KB."
return 0
else
echo "Not enough space on backup drive. Required: $required_space KB, Available: $available_space KB. Manual backup necessary"
echo $RSYNC_CMD
exit 1
fi
}
# Initial check
check_mount
if [ $? -eq 1 ]; then
# If the drive is not mounted, prompt the user
echo "Please mount drive within one minute."
# Wait for up to 60 seconds for the drive to be mounted
for i in {1..60}; do
# check every second if drive is mounted
sleep 1
check_mount
if [ $? -eq 0 ]; then
# if enough space available, execute rsync, else print error message
check_space
if [ $? -eq 0 ]; then
eval $RSYNC_CMD
exit 0
fi
fi
done
fi
# If the drive is still not mounted after 60 seconds, print an error message
if [ $? -eq 1 ]; then
echo "Backup drive is not mounted. Could not backup /home/ironman/. Command for manual backup:"
echo $RSYNC_CMD
exit 1
fi
# if enough space available, execute rsync, else exit script
check_space
if [ $? -eq 0 ]; then
eval $RSYNC_CMD
exit 0
fi
我在末尾添加了以下行/etc/anacrontab
:
@monthly 15 backup.monthly nice /home/ironman/scripts/backup_anacron.sh
当我强制运行每月任务时/usr/sbin/anacron -n -f cron.monthly
,什么也没发生。我做错了什么?