This is a script that copies directories from A to B. It does not compress directories into an archive, though you are welcome to adapt your script using snippets from this post.
The following is a bash script that mounts an external storage device for you (given the /dev/sda1
device name), copies files contained in a SOURCE
directory to a DESTINATION
directory.
You can specify files to ignore in a separate rsync-ignore.txt
file. Check out this post for the various ways you can exclude files with rsync
.
#!/bin/bash
MOUNTDIR="/home/pi/ssd"
DEVICE="/dev/sda1"
SOURCE="/home/pi/documents/*"
DESTINATION="$MOUNTDIR/documents"
DIR=$(ls $SOURCE)
#echo "DIR: $DIR"
if [ -n "$DIR" ]; then
if [ $(mount | grep -c $MOUNTDIR) != 1 ]
then
echo "Mounting $DEVICE"
mount -t exfat $DEVICE $MOUNTDIR || exit 1
echo "$MOUNTDIR is now mounted"
else
echo "$MOUNTDIR already mounted"
fi
echo "Commencing copy of files"
rsync -ahvWi --exclude-from='rsync-ignore.txt' --progress $SOURCE $DESTINATION
umount $MOUNTDIR
else
echo "The directory is empty."
fi
You can find out where your device is mounted by running tail -f /var/log/syslog
and checking the mount location log entry when you plug in your storage device.
{: .notice–info}
rsync-ignore.txt Add and remove files types to exclude. THis file must be in the same directory as your bash script.
*.txt
*.jpeg
*.jpg
*.png
*.exe
*.msi
*.deb
*.gif
Automatic execution using Crontab
Type crontab -e
, and paste this:
0 2 * * * /bin/bash /home/pi/rsync-script.sh
This will run your script daily at 2 am.