
The source code of a basic Linux shell backup script is shown below. It creates a compressed archive of the specified user's home directory and provides a summary of the backup process.
BASH
#!/bin/bash
# If no username is given, use the current user
if [ -z "$1" ]; then
user=$(whoami)
else
if [ ! -d "/home/$1" ]; then
echo "$1 directory does not exist"
exit 1
fi
user=$1
fi
input="/home/$user"
out="/tmp/${user}_backup_$(date +%Y-%m-%d_%H%M%S).tar.gz"
# Count total files in source directory
function count_files {
find "$1" -type f | wc -l
}
# Count total directories in source
function count_dirs {
find "$1" -type d | wc -l
}
# Count directories in archive
function archive_dirs {
tar -tzf "$1" | grep /$ | wc -l
}
# Count files in archive
function archive_files {
tar -tzf "$1" | grep -v /$ | wc -l
}
# Create archive and suppress error output
tar -czf "$out" "$input" 2> /dev/null
# Gather statistics
src_files=$(count_files "$input")
src_dirs=$(count_dirs "$input")
arc_dirs=$(archive_dirs "$out")
arc_files=$(archive_files "$out")
# Output results
echo "####### $user #######"
echo "$src_files files were added to the archive"
echo "$src_dirs directories were added to the archive"
if [ "$src_files" -eq "$arc_files" ]; then
echo "$input has been successfully backed up"
ls -l "$out"
else
echo "Backup failed"
fi
Related Articles

Useful CSF SSH Commands
0 Comments

Hotlink Protection (with .htaccess)
0 Comments
Comments ()
No comments yet. Be the first to comment!