Your go-to source for expert Bash scripts.
Bash Scripting GPT: Expert-Grade, Search-Friendly Scripts for Direct Implementation.
Shell Expert Pro is designed for simplicity and ease of use, making script generation effortless.
Every script is crafted with industry best practices in mind, ensuring reliability and efficiency.
Those new to Bash scripting will find Shell Expert Pro a great learning tool.
Experienced developers can leverage Shell Expert Pro to streamline their workflow.
#!/bin/bash
# Backup and Restore Script
# Usage:
# To backup: ./script.sh --source [source_dir] --destination [destination_dir] --backup
# To restore: ./script.sh --source [source_dir] --destination [destination_dir] --restore
main() {
parse_arguments "$@"
if [[ $BACKUP -eq 1 ]]; then
backup_files
elif [[ $RESTORE -eq 1 ]]; then
confirm_restore && restore_files
else
printf "Invalid operation. Please specify either --backup or --restore.\n" >&2
return 1
fi
}
parse_arguments() {
while [[ $# -gt 0 ]]; do
case "$1" in
--source)
SOURCE_DIR="$2"
shift 2
;;
--destination)
DESTINATION_DIR="$2"
shift 2
;;
--backup)
BACKUP=1
shift
;;
--restore)
RESTORE=1
shift
;;
*)
printf "Invalid argument: $1\n" >&2
return 1
;;
esac
done
if [[ -z $SOURCE_DIR || -z $DESTINATION_DIR ]]; then
printf "Both source and destination directories are required.\n" >&2
return 1
fi
}
backup_files() {
if ! mkdir -p "$DESTINATION_DIR"; then
printf "Failed to create destination directory.\n" >&2
return 1
fi
if ! tar -czf "${DESTINATION_DIR}/backup.tar.gz" -C "$SOURCE_DIR" .; then
printf "Backup failed.\n" >&2
return 1
fi
printf "Backup completed successfully.\n"
}
confirm_restore() {
read -p "Are you sure you want to restore files to ${SOURCE_DIR}? [y/N] " confirmation
[[ $confirmation == [Yy]* ]]
}
restore_files() {
if ! tar -xzf "${DESTINATION_DIR}/backup.tar.gz" -C "$SOURCE_DIR"; then
printf "Restore failed.\n" >&2
return 1
fi
printf "Restore completed successfully.\n"
}
main "$@"
This website uses cookies to enhance your experience. By continuing to browse, you agree to our use of cookies.