I have a simple bash script which copies files using rsync:
#! /bin/bash
read -p "enter source: " sdir
read -p "enter target: " tdir
read -p "enter name of log file: " lfile
current_date=$(date +%Y-%m-%d)
rsync_options="-avb --exclude Documents --exclude Desktop --exclude Music --exclude Downloads --exclude Videos --exclude Backgrounds --exclude Pictures --exclude .cache --exclude .cabal --backup-dir $target/current_date --delete"
$(which rsync) $rsync_options $sdir $tdir/$current_date.$lfile >> /home/paul/Documents/logs/backup_$current_date.$lfile
When I run this, I get
paul on arch ~ took 8s
10:07 ❯ backup1.sh
enter source: ~/
enter target: /run/media/paul/7b266343-ee12-4e6b-bff5-77307f299ba0/Vostro/
enter name of log file: home
rsync: [sender] change_dir "/home/paul/~" failed: No such file or directory (2)
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1338) [sender=3.3.0]
However, when I delete $sdir and write in the actual directory ~/, the script runs as expected. Why is the variable $sdir not passed, but the others are?
I tried running the script from several directories, although I do not see that this would make a difference. I rewrote this script with the read bit:
#! /bin/bash
if [ $# -ne 3 ]
then
echo "Usage: backup.sh <source_directory> >target_directory>"
echo "Please try again."
exit 1
fi
if ! command -v rsync > /dev/null 2>&1
then echo "This script requires rsync"
exit 2
fi
current_date=$(date +%Y-%m-%d)
rsync_options="-avb --exclude Documents --exclude Desktop --exclude Music --exclude Downloads --exclude Videos --exclude Backgrounds --exclude Pictures --exclude .cache --exclude .cabal --backup-dir $2/current_date --delete"
$(which rsync) $rsync_options $1 $2/$current_date.$3 >> /home/paul/Documents/logs/backup_$current_date.$3.log
# run this script doing something like: backup.sh /home/paul /run/media/paul/7b266343-ee12-4e6b-bff5-77307f299ba0 paul
and this worked as expected