Bash Alias: Make and Restore Backups
2025-02-04
---
I often find myself needing to create temporary backups of files or directories. The way I usually do this is by appending its name with the date and a ".bak" extension. It can be tedious to do that over and over again, especially when I'm testing a program or script; I'd much rather automate backups with one command.
Today I put together a Bash alias to do just that:
function mkbak() {
restoreBackup=0
case "${1}" in
-r|--restore) restoreBackup=1; shift; continue;;
*) ;;
esac
if [ $restoreBackup -eq 1 ]; then
for backup in "$@"; do
[ -e "${backup}" ] && { rm -fr "${backup%_*}"; mv "${backup}" "${backup%_*}"; }
done
else
for original in "$@"; do
[ -f "${original}" ] && cp "${original}" "${original}_$(date +"%Y%m%d-%H%M%S").bak"
[ -d "${original}" ] && { originalNoTrailingSlash="${original%"${original##*[!/]}"}"; cp -R "${original}" "${originalNoTrailingSlash}_$(date +"%Y%m%d-%H%M%S").bak"; }
done
fi
}
This alias can back up or restore multiple files or directories at once. The process of restoring a backup requires deleting the original first; otherwise `mv` behaves unexpectedly when restoring a directory.
---
[Last updated: 2025-02-05]