33. Building a Practical Automation Script (Automated Backup)
Let's apply our scripting knowledge to create a useful script: backing up our Termux home directory to the Android shared storage.
Prerequisites
Ensure you have run termux-setup-storage and know your shared storage path (~/storage/shared).
The Backup Script (termux_backup.sh)
We will use the tar command for archiving and compression.
bash $ nano termux_backup.sh
Content:
bash #!/bin/bash
--- Configuration Variables ---
BACKUP_DIR="/data/data/com.termux/files/home" TARGET_DIR="/data/data/com.termux/files/home/storage/downloads/Termux_Backups" DATE_STAMP=$(date +%Y-%m-%d_%H%M%S) BACKUP_FILE="termux_backup_${DATE_STAMP}.tar.gz"
echo "Starting Termux Home Backup..."
1. Create target directory if it doesn't exist
if [ ! -d "$TARGET_DIR" ]; then mkdir -p "$TARGET_DIR" echo "Created target directory: $TARGET_DIR" fi
2. Create the compressed archive (excluding the backup folder itself)
-c: create, -z: compress (gzip), -v: verbose, -f: filename
cd $BACKUP_DIR tar -czvf "$TARGET_DIR/$BACKUP_FILE" --exclude='storage' --exclude='Termux_Backups' ./*
if [ $? -eq 0 ]; then echo "\nSUCCESS: Backup created at $TARGET_DIR/$BACKUP_FILE" echo "Size: $(du -h $TARGET_DIR/$BACKUP_FILE | awk '{print $1}')" else echo "\nERROR: Backup failed." fi
Make executable: chmod +x termux_backup.sh
Run: ./termux_backup.sh
This script demonstrates variables, conditionals, and external commands (tar, du, awk) working together for automation.