Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # The script receives the path to a file, creates a backup folder in
- # the folder where the file is, creates a folder whose name is the
- # same as the basename of the file and, in the folder, makes a copy of
- # the file with a timestamp as the new basename. The script expects
- # that espeak and gio should be installed. If espeak isn't installed
- # the script will try to use notify-send instead. If gio isn't
- # installed the script will skip marking the backup folder with an
- # icon.
- ####### Functions #######
- function announce()
- {
- if command -v espeak; then
- espeak -v whisper "$1"
- else
- notify-send "Backups" "$1" \
- -u "normal" \
- -i "dialog-information" \
- -t 3000
- fi
- }
- function leave()
- {
- if [ "$2" -eq 1 ]; then
- announcement_text="${1} Exiting!"
- else
- announcement_text="$1"
- fi
- announce "$announcement_text"
- exit "$2"
- }
- ####### Main #######
- PATH_TO_SOURCE_FILE="$1"
- if [ -d "$PATH_TO_SOURCE_FILE" ]; then
- leave "The target object is not a file." 1
- fi
- PATH_TO_SOURCE_FILE_DIRECTORY="${PATH_TO_SOURCE_FILE%/*}"
- cd "$PATH_TO_SOURCE_FILE_DIRECTORY" || \
- leave "Couldn't switch to the target directory." 1
- BACKUP_FILE_BASENAME=$(date +%F_%T)
- FILE_EXTENSION=${PATH_TO_SOURCE_FILE##*.}
- BACKUP_FILE_DIRECTORY_NAME=$(basename "$PATH_TO_SOURCE_FILE" ".${FILE_EXTENSION}")
- BACKUP_DIRECTORY_PATH="backup/${BACKUP_FILE_DIRECTORY_NAME}"
- mkdir -p -- "$BACKUP_DIRECTORY_PATH" || leave "Couldn't create a directory." 1
- if command -v gio; then
- gio set "backup" -t stringv metadata::emblems "emblem-package"
- touch "backup"
- else
- announce "Gio is not installed. The root backup folder won't be marked with \
- the 'emblem-package' icon. No big deal actually."
- fi
- BACKUP_FILE_PATH="${BACKUP_DIRECTORY_PATH}/${BACKUP_FILE_BASENAME}.${FILE_EXTENSION}"
- LAST_BACKUP_FILE=$(find "$BACKUP_DIRECTORY_PATH" -maxdepth 1 -type f | sort | tail -n 1)
- if cmp "$PATH_TO_SOURCE_FILE" "$LAST_BACKUP_FILE"; then
- leave "The backup is up-to-date." 1
- else
- cp -- "$PATH_TO_SOURCE_FILE" "$BACKUP_FILE_PATH" || \
- leave "Couldn't copy the file." 1
- fi
- leave "Done!" 0
Advertisement