This guide provides a thorough tutorial on creating a Bash script for backing up files to another directory. This script also integrates user-provided custom options and settings for flexibility and scalability.
Prerequisites
Ensure that you have sufficient privileges to read the files you intend to back up and write permissions on the directory where the backup will be stored.
Script Details
This script performs the following steps:
- It takes input parameters for source and destination directories.
- It verifies the existence and accessibility of these directories.
- It offers options for various backup modes – copy only new and updated files, copy all files, and more.
- It executes the backup process according to the selected mode.
Script Structure
Here’s the basic structure of the script:
#!/bin/bash
# User input
source_directory=$1
destination_directory=$2
backup_mode=$3
# Validate directories and backup mode
#...
# Perform backup based on mode
#...
This script expects three arguments: source directory, destination directory, and backup mode.
Detailed Code and Explanation
#!/bin/bash
# User input
source_directory=$1
destination_directory=$2
backup_mode=$3
# Validate input directories
if [ ! -d "$source_directory" ]; then
echo "Source directory does not exist."
exit 1
fi
if [ ! -d "$destination_directory" ]; then
echo "Destination directory does not exist."
exit 1
fi
# Validate backup mode
valid_modes=("all" "new" "update")
if [[ ! " ${valid_modes[@]} " =~ " ${backup_mode} " ]]; then
echo "Invalid backup mode. Valid modes are 'all', 'new', and 'update'."
exit 1
fi
# Perform backup based on mode
case $backup_mode in
all)
rsync -av $source_directory $destination_directory
;;
new)
rsync -av --ignore-existing $source_directory $destination_directory
;;
update)
rsync -avu $source_directory $destination_directory
;;
esac
The rsync
command performs the actual copying of files. -av
flags make rsync
run in verbose mode and preserve file permissions and other attributes. The --ignore-existing
flag for the ‘new’ mode prevents rsync
from overwriting files in the destination that already exist. The -u
flag for ‘update’ mode makes rsync
skip files that are newer on the destination side.
Running the Script
To execute the script, use the command:
bash backup_script.sh /path/to/source_directory /path/to/destination_directory backup_mode
Replace backup_script.sh
with the name of your script, /path/to/source_directory
with the path of your source directory, /path/to/destination_directory
with the path of your destination directory, and backup_mode
with one of ‘all’, ‘new’, or ‘update’.
Conclusion
This Bash script provides a basic but flexible solution for backing up files to another directory. Please note that the script does not cover aspects like error handling during the actual copying process or logging. For a more production-ready script, these features should be implemented.