Backup Script in Shell

Level 5248 keystrokes

Creates a timestamped .tar.gz archive of /var/www in /backup, deletes archives older than 7 days, and shows the new file. The timestamp and file size in the output vary.

Shell code

# Directory to back up
1src="/var/www"
# Where the archives are stored
2dest="/backup"
# Timestamp such as 20240115_103045
3date=$(date +%Y%m%d_%H%M%S)
# Full path of the new archive
4archive="$dest/backup_$date.tar.gz"
# -czf creates a gzip archive; -C /var with www stores paths as www/...
5tar -czf "$archive" -C "$(dirname "$src")" "$(basename "$src")"
# Delete archives last modified more than 7 days ago
6find "$dest" -name "*.tar.gz" -mtime +7 -delete
# Report the new archive and its size (-h = human-readable)
7echo "Created: $archive"
8ls -lh "$archive"

Output

Created: /backup/backup_20240115_103045.tar.gz
-rw-r--r-- 1 user user 15M Jan 15 10:30 /backup/backup_20240115_103045.tar.gz
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • "× 24
  • $× 11
  • -× 6
  • %× 6
  • .× 4
  • /× 4
  • =× 4
  • (× 3
  • )× 3
  • _× 2

More Shell examples at level 5

← Shell typing practice