Example of a shell script that backs up a specific directory to a destination directory, creating a new backup directory based on the current date:
Shell script:
#!/bin/bash
# Check if source and destination directories have been provided
if [ $# -ne 2 ]
then
echo "Usage: $0 <source-dir> <dest-dir>"
exit 1
fi
SOURCE_DIR="$1"
DEST_DIR="$2"
# Check if the provided source directory exists
if [ ! -d "$SOURCE_DIR" ]
then
echo "The source directory $SOURCE_DIR does not exist."
exit 1
fi
# Check if the provided destination directory exists
if [ ! -d "$DEST_DIR" ]
then
echo "The destination directory $DEST_DIR does not exist."
exit 1
fi
# Generate the name of the backup directory
BACKUP_DIR="backup_$(date +%Y%m%d%H%M%S)"
# Create the backup directory
mkdir -p "$DEST_DIR/$BACKUP_DIR"
# Copy the contents of the source directory to the backup directory
cp -r "$SOURCE_DIR/"* "$DEST_DIR/$BACKUP_DIR"
echo "Backup of $SOURCE_DIR completed in $DEST_DIR/$BACKUP_DIR"
This script takes two arguments: the source directory that you want to back up, and the destination directory where you want to store the backup. The script checks if both directories exist. If they do, the script creates a new directory in the destination directory with a name based on the current date and time (in the format backup_YYYYMMDDHHMMSS), and copies the contents of the source directory into this new backup directory.
This kind of script can be useful for creating timed backups of important data. It uses cp to copy files, which means that it doesn’t handle things like incremental backups or file deduplication.
Other urls to refer