Automate Everything in Zsh — Backup, Maintain, Deploy #27
Video: Automate Everything in Zsh — Backup, Maintain, Deploy #27 by Taught by Celeste AI - AI Coding Coach
Watch full page →Automate Everything in Zsh — Backup, Maintain, Deploy
In this tutorial, you'll learn how to create practical automation scripts using Zsh to streamline backup, system maintenance, and deployment tasks. We'll cover writing backup scripts with tar and retention policies, automating log rotation and health checks for maintenance, and building deployment workflows that include dependency verification and rollback capabilities.
Code
# Backup script with retention policy
backup_dir="$HOME/backups"
source_dir="$HOME/projects"
date_stamp=$(date +%Y-%m-%d)
backup_file="$backup_dir/backup-$date_stamp.tar.gz"
retention_days=7
mkdir -p $backup_dir
# Create a compressed tarball of the source directory
tar -czf $backup_file $source_dir
# Remove backups older than retention_days
find $backup_dir -type f -name "backup-*.tar.gz" -mtime +$retention_days -exec rm {} \;
# Maintenance script: rotate logs and check disk usage
log_dir="/var/log/myapp"
max_log_size=10485760 # 10MB
for log in $log_dir/*.log; do
if [[ -f $log && $(stat -c%s $log) -gt $max_log_size ]]; then
mv $log "$log.$(date +%Y%m%d%H%M%S)"
gzip "$log.$(date +%Y%m%d%H%M%S)"
touch $log
fi
done
# Simple health check: disk usage alert
disk_usage=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
if (( disk_usage > 80 )); then
echo "Warning: Disk usage is above 80% ($disk_usage%)"
fi
# Deployment script with dependency check and rollback
deploy_dir="/var/www/myapp"
backup_deploy="$deploy_dir-backup-$(date +%Y%m%d%H%M%S)"
new_release="/tmp/myapp_release"
# Check for required dependency
if ! command -v node &> /dev/null; then
echo "Error: Node.js is not installed. Aborting deployment."
exit 1
fi
# Backup current deployment
if [[ -d $deploy_dir ]]; then
mv $deploy_dir $backup_deploy
fi
# Deploy new release
mv $new_release $deploy_dir
# Simple test to verify deployment success
if ! curl -sSf http://localhost/healthcheck; then
echo "Deployment failed, rolling back..."
rm -rf $deploy_dir
mv $backup_deploy $deploy_dir
else
echo "Deployment succeeded."
rm -rf $backup_deploy
fi
Key Points
- Use tar with date-stamped filenames and find with mtime to automate backups and retention cleanup.
- Automate log rotation by renaming and compressing large log files, then creating new empty logs.
- Implement health checks like disk usage monitoring to proactively detect system issues.
- In deployment scripts, verify dependencies before proceeding to avoid failures.
- Include backup and rollback mechanisms to safely deploy new releases and recover from errors.