Skip to content

Instantly share code, notes, and snippets.

@odinokov
Last active June 9, 2024 15:09
Show Gist options
  • Save odinokov/facf57bfa2f757ea63f01da213d89a21 to your computer and use it in GitHub Desktop.
Save odinokov/facf57bfa2f757ea63f01da213d89a21 to your computer and use it in GitHub Desktop.
Script to archive a specified directory as a tar.gz
#!/bin/bash
# Script to archive a specified directory
# Ensure the script exits immediately if any command fails
set -e
# Cleanup function
cleanup() {
[ -f "$temp_file" ] && rm "$temp_file"
}
# Trap to execute cleanup on script exit
trap cleanup EXIT
# Default CPU count for compression
DEFAULT_CPU=$(( $(grep ^cpu\\scores /proc/cpuinfo | uniq | awk '{print $4}') ))
DEFAULT_CPU=$((DEFAULT_CPU>8 ? 8 : DEFAULT_CPU-1))
# Function to display help
show_help() {
cat << EOF
Usage: $0 <target_directory> [destination_directory]
This script archives the specified directory.
Arguments:
target_directory: The full path of the directory to archive.
destination_directory: The directory where the archive will be stored (optional).
EOF
}
# Function containing the main script logic
main() {
# Check if required commands are available
required_commands=("tar" "pv" "crabz" "du" "cut" "basename" "dirname" "date" "mv")
for cmd in "${required_commands[@]}"; do
if ! command -v "$cmd" &> /dev/null; then
echo "Error: Required command '$cmd' is not available." >&2
return 1
fi
done
# Check for minimum argument
if [ "$#" -lt 1 ]; then
show_help
return 1
fi
target_dir="$1"
dest_dir="${2:-.}" # Use current directory if destination is not provided
target_dir=$(realpath "$target_dir")
dest_dir=$(realpath "$dest_dir")
# Check if the target directory exists
if [ ! -d "$target_dir" ]; then
echo "Error: The target directory does not exist." >&2
return 1
fi
# Check for available disk space
required_space=$(du -sb "$target_dir" | cut -f1)
available_space=$(df "$dest_dir" | awk 'NR==2 {print $4}')
if [ "$available_space" -lt "$required_space" ]; then
echo "Warning: Not enough space on the destination. Trying to proceed..."
fi
# Archiving process
output_file="$dest_dir/backup_$(basename "$target_dir")_$(date +"%Y_%m_%d_%I_%M_%p").tar.gz"
temp_file="$output_file.tmp"
echo "Starting backup of '$target_dir'..."
ionice -c 2 -n 0 tar -I "pv -s $required_space | ionice -c 2 -n 0 crabz -l9 -p$DEFAULT_CPU" -cf "$temp_file" -C "$(dirname "$target_dir")" "$(basename "$target_dir")" \
&& mv "$temp_file" "$output_file" \
&& echo "Backup created successfully at $output_file"
}
# Execute the main function and handle script failure
main "$@" || echo "Error: Script failed!" >&2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment