I am working with Debian distro. I have wrote a backup bash script that implements snapshot rotation, it works like a charm when calling it interactively from shell but fails when invoked from cron job(of root user). In few places, in the script, I generate the target paths strings in this way, examples:
btrfs subvolume snapshot "$1/current" "$BASENAME-1"
or
btrfs subvolume delete "$BASENAME-$NUM_BAK"
In the first case I create the first daily snapshot and in the second case I delete the last snapshot, which number is stored in the NUM_BAK var. The script file, as usual, starts with:
#!/bin/bash
But I have noticed that when invoked interactively the "$BASENAME-1"
, when $BASENAME
is "/mnt/backup/daily", the final string become /mnt/backup/daily-1
, when executed in cron the generated string becomes /mnt/backup/daily-
with no final number.
The crontab line is:
52 1 0 * * * /root/backup-script/backupscipt.sh oneparam 2>&1 1>/mnt/logstuff/lastrun.log
I have tried different solutions.
1) Changin' crontab entry to:
52 1 0 * * * /bin/bash /root/backup-script/backup.sh oneparam 2>&1 1>/mnt/logstuff/lastrun.log
2) Adding in crontab, first than the cron entry, this ones (as suggested here):
BASH_ENV="/root/.bashrc"
SHELL=/bin/bash
I'm not a shell expert and first to change all this bash script to a more 'deterministic' python script I like to understand where the problem is.
EDIT (Thanks for suggestions): I created a pruned version of my backup script that focuses on the string substitution. But the problem has disappeared.. I have to track down the problem to mysterious interactions. I'll update this question when I have more proofs.
#!/bin/bash
#Configurations:
BACKUP_PATH='/mnt/backup'
NUM_DAYS=5; #number of total days
backup (){
BASENAME="$1/$2"
NUM_BAK=$3
#Clean older backup-snapshot
echo "basename for backup is $BASENAME"
echo "expect to delete: daily-5"
echo "to delete: $BASENAME-$NUM_BAK"
#real operation omitted
for i in $(seq $(($NUM_BAK-1)) -1 1); do
#Shift backups 2->3 1->2 and so on
#with + works as expected
echo "Shifting $BASENAME $i to $i+1"
done
#I expect .../daily-1 from the following:
echo "expecting snapshot name daily-1"
echo "creating the snapshot $BASENAME-1"
}
echo "Synching remote folder to current"
#rsync part omitted...
#...
#end rsync part
echo "Daily backup rotation started"
backup $BACKUP_PATH "daily" $NUM_DAYS