I am new to bash, so I'm a bit lost with this script I made to backup some directories from the local machine into a NAS. The NAS will contain only a certain number of backed up files, so before copying a new one I delete the oldest of the existing.
First of all the script defines all the paths, directory and file names into variables
# Defines directories
ORIGEN='/Library/path-to-directories/'
DESTINAS='/Volumes/path-to-backup/'
DESTITAR='/Library/path-to-temp/'
# Defines names of the files and folders to delete (OLDDIR) and copy (NEWDIR)
OLDTAR=`/bin/ls /Volumes/path-to-backup/ | head -n 1`
NEWDIR=`/bin/ls /Library/path-to-directories/ | tail -n 1`
Then using the variable names it: Creates a tar compressed file from the original directory. The tar file is kept in a separate, temporary directory.
/usr/bin/sudo /usr/bin/tar -czf "$DESTITAR$NEWDIR.tgz" "$ORIGEN$NEWDIR"
Deletes the older of the tar files from the NAS:
/usr/bin/sudo /bin/rm $DESTINAS$OLDTAR
Copies the tar file into the NAS:
/usr/bin/sudo /bin/cp -Rp "$DESTITAR$NEWDIR.tgz" $DESTINAS
Deletes the tar file from the temp directory:
/usr/bin/sudo /bin/rm -f "$DESTITAR$NEWDIR.tgz"
The script is run unattended by a user that has been duly authorized through changes in the sudoers file. Everything runs smoothly except in this step:
/usr/bin/sudo /bin/rm $DESTINAS$OLDTAR
The log file shows no errors but there's nothing in the place of the $OLDTAR
variable, like it is not resolved, so it actually executes:
/usr/bin/sudo /bin/rm /Volumes/path-to-backup/
However if I run the commands in the terminal one by one I get it to work well. It may be a problem of user permissions?
rm
command, useecho $DESTINAS$OLDTAR
what does it output?filename_YYYY-MM-DD_HHMM.tgz
if [ -f $DESTINAS$OLDTAR ] then rm -f "$DESTITAR$NEWDIR.tgz" else echo "file not there" fi
Add that conditional statement to your script