You've got a few issues with coding practice in your code.
- You'd want to check for the success of those commands especially when the next command depends on the success of the previous one.
- Leaving a variable unquoted in list context is asking the shell to split it and perform filename generation on it, there's no reason you'd want to do that here.
Now about rm -r
, it's mean to delete the directory and all its content. It will not follow symlinks when doing so. Even if /home/fauna/backup/$oldday
is a symlink, only that symlink is removed. That's probably what you want here. It would be different if you did rm -r "/home/fauna/backup/$oldday/"
(with the trailing /
).
However, without -f
, that that means that if stdin is a terminal, you could be prompted for the removal of non-writable files. So, if it's meant to be an unattended script, you should probably add it. Also with -f
, rm
only reports failure if the directory if still there afterwards.
#!/bin/sh -
day=$(date +%m%d%y) || exit
oldday=$(date -d "-4 days" +%m%d%y) || exit
# date is very unlikely to fail, but if it does, it would have dramatic consequences
# shouldn't access to those directories be restricted (if it hasn't been
# restricted already some levels above)?
# umask 077
mkdir -p "/home/fauna/backup/$day" || exit
# with -p, mkdir would only fail if the directory is not there after that call.
# It may not be what you want though. You may want mkdir to fail if the
# directory already existed in which case you'd want to omit the -p.
cp /home/fauna/backup/backup.sh "/home/fauna/backup/$day" || exit
cd "/home/fauna/backup/$day" || exit
./backup.sh || exit
# only delete the old one if the new one succeeds.
rm -rf "/home/fauna/backup/$oldday"
Note that here since we're adding || exit
to every command, we might as well use set -e
which causes the shell to exit upon any error of any command, but I prefer || exit
as it makes it explicit that you've given consideration into error handling (and set -e
has too many gotchas to be used reliably (not in this simple case here though)).