Automating Backups with Bash

Su Suriya Ravichandran Updated 06 Dec 2026
17 min read ·Lesson 164 of 205

A backup is a copy of data, kept somewhere else, that you can use to get the data back after it is deleted, corrupted, encrypted by ransomware or lost with a failed disk. Backups only protect you if they actually happen, on time, every time, so they are one of the most common things people automate with Bash. A backup script combines many skills from this tutorial: building commands from variables, checking exit statuses, handling file names safely, working with dates, logging and cleaning up after failures.

This lesson explains what a good backup must guarantee, how the standard Linux tools (tar, compression programs, sha256sum) create and verify backup archives, how incremental backups and retention work, and then builds a complete backup script that can run unattended from a scheduler.

Understanding the Concept

A backup is only useful if you can restore from it. That simple test leads to a list of requirements:

RequirementWhy it matters
Completeit includes everything needed to rebuild the data, and nothing important is silently skipped
Consistentfiles are not captured halfway through being written
Verifiedthe archive is known to be readable and undamaged
Separateit is stored on a different disk, and ideally a different machine or site, from the original
Retainedseveral older versions are kept, so a problem noticed late can still be undone
Privateits permissions protect the data as well as the original's do
Automaticit runs without anyone remembering to start it, and failures are reported
Testedsomeone has actually restored from it

A widely used rule of thumb is 3-2-1: keep three copies of important data, on two different types of storage, with one copy off-site. A Bash script usually handles the first steps: creating the archive locally and verifying it. Copying it to another machine or to cloud storage is then a second, separate step.

Choosing What to Back Up

Back up the data that cannot be recreated, and leave out what can:

  • Include: user files and uploads, configuration (/etc, application config files), application data, database dumps, scripts and crontabs.
  • Exclude: caches, temporary files, build output, log files you do not need, package folders such as node_modules that can be reinstalled, and the backup folder itself.

Databases need special care. Copying the files of a running database server can capture them in an inconsistent state. Instead, use the database's own dump tool (for example mysqldump or pg_dump) to write a consistent export to a file, and back up that file.

Creating an Archive with tar

tar (tape archive) packs a folder tree, including file names, permissions, owners and timestamps, into a single file. The -z option compresses it with gzip. The site folder used in this lesson contains html/index.html, uploads/my photo.jpg, app.conf and a cache folder:

ts=$(date +%Y%m%d-%H%M%S)
tar -czf "backups/site-$ts.tar.gz" -C /srv/t164 --exclude='site/cache' site
tar -tzf "backups/site-$ts.tar.gz"
site/
site/html/
site/html/index.html
site/uploads/
site/uploads/my photo.jpg
site/app.conf

The options in detail:

  • -c creates an archive, -z compresses it with gzip, and -f FILE names the archive file. -t lists the contents instead of creating.
  • -C /srv/t164 changes into that folder before adding files, so the archive stores the relative path site/.... Archives with relative paths can be restored anywhere.
  • --exclude=PATTERN skips matching paths. Put --exclude options before the names of the files to archive, because GNU tar applies them only to names that follow.
  • The timestamp in the file name (site-20261124-105943.tar.gz) makes every archive name unique and lets names sort in date order. The format %Y%m%d-%H%M%S sorts correctly as plain text.

If you give tar an absolute path instead, it removes the leading slash and warns you:

tar -czf backups/abs.tar.gz /srv/t164/site/app.conf
tar -tzf backups/abs.tar.gz
tar: Removing leading `/' from member names
srv/t164/site/app.conf

This protects you during a restore, because extracting the archive cannot overwrite files in / by accident. Using -C is cleaner and avoids the warning.

Compression choices

OptionProgramTypical use
-zgzipfast, available everywhere; the safe default
-Jxzmuch smaller archives, but much slower to create
--zstdzstdclose to xz in size and faster than gzip, if zstd is installed
(none)no compressiondata that is already compressed, such as photos and videos

The file name extension should match: .tar.gz, .tar.xz, .tar.zst or .tar.

tar's exit status

GNU tar uses three exit statuses, and a backup script must handle them differently:

StatusMeaning
0success
1some files changed while tar was reading them; the archive is complete, but those files may be inconsistent
2a fatal error, such as an unreadable file or a full disk; the archive cannot be trusted

Treating status 1 as a warning and status 2 as a failure is the usual approach.

Verifying a Backup

An archive that cannot be read is worse than no archive, because it gives false confidence. Three checks, from quickest to most thorough:

gzip -t "backups/site-$ts.tar.gz" && echo "gzip ok"
(cd backups && sha256sum "site-$ts.tar.gz" > "site-$ts.tar.gz.sha256" && sha256sum -c "site-$ts.tar.gz.sha256")
gzip ok
site-20261124-105943.tar.gz: OK
  • gzip -t tests the compressed data without extracting anything.
  • tar -tzf ARCHIVE > /dev/null reads the whole archive and checks its structure.
  • A checksum file made with sha256sum records a fingerprint of the archive. Later, for example after copying it to another server, sha256sum -c proves that the copy is identical. The .sha256 file stores the file name without a folder, which is why the commands run inside backups with cd.

To see what these checks catch, four bytes in the middle of a copy of an archive were overwritten with zeros:

sha256sum -c bad.sha256; echo "sha status $?"
gzip -t bad.tar.gz; echo "gzip -t status $?"
tar -tzf bad.tar.gz >/dev/null; echo "tar -t status $?"
bad.tar.gz: FAILED
sha256sum: WARNING: 1 computed checksum did NOT match
sha status 1

gzip: bad.tar.gz: invalid compressed data--format violated
gzip -t status 1

gzip: stdin: invalid compressed data--format violated
tar: Child returned status 1
tar: Error is not recoverable: exiting now
tar -t status 2

All three detected the damage. The final and best test is a real restore: extract the archive into an empty folder and compare it with the original, for example with diff -r. Do this regularly, not only when you need the data.

Full and Incremental Backups

A full backup copies everything each time. It is simple and each archive restores on its own, but it takes the most time and space. An incremental backup copies only what changed since the previous backup.

GNU tar supports incremental backups with --listed-incremental=SNAPSHOT_FILE. The snapshot file records the state of every file, and the next run uses it to decide what changed:

tar -czf inc/level0.tar.gz --listed-incremental=inc/site.snar -C /srv/t164 site
echo "full: $(tar -tzf inc/level0.tar.gz | wc -l) entries"
echo 'new post' > site/html/post.html; echo '<h1>Home v2</h1>' > site/html/index.html
tar -czf inc/level1.tar.gz --listed-incremental=inc/site.snar -C /srv/t164 site
tar -tzf inc/level1.tar.gz
full: 8 entries
site/
site/cache/
site/html/
site/uploads/
site/html/index.html
site/html/post.html

The first run, with no snapshot file yet, made a full (level 0) backup. The second archive contains only the two changed files, plus the folder entries tar needs to record the structure. To restore, extract the full archive and then every incremental archive in order, with --listed-incremental=/dev/null so tar also applies deletions recorded in the increments:

mkdir -p restore
tar -xzf inc/level0.tar.gz -C restore --listed-incremental=/dev/null
tar -xzf inc/level1.tar.gz -C restore --listed-incremental=/dev/null
diff -r site restore/site && echo "restore matches source"
restore matches source

Every incremental archive depends on all the archives before it, so losing one breaks the chain. A common schedule makes a full backup weekly and incremental backups daily, and keeps each week's chain together.

Mirrors with rsync

rsync is the other standard backup tool. Instead of creating archive files, it makes a destination folder match a source folder, copying only the differences, also across SSH to another machine. rsync --archive --delete SRC/ DEST/ keeps an exact mirror. A mirror alone is not a full backup: if a file is deleted or damaged at the source, the next run copies that change to the mirror too. The --link-dest option solves this by creating a new dated folder for each run, where unchanged files are hard links to the previous run's copies, so every snapshot looks complete while only changed files take new space.

Retention: Keeping the Right Number of Backups

Without cleanup, backups eventually fill the disk, and then the newest backup fails. Retention removes archives beyond a limit, either by count ("keep the 7 newest") or by age ("delete anything older than 30 days", lesson 165). Retention code deletes files, so it needs the same care as any destructive command (lesson 160):

  • Match only this job's archives, with an exact pattern. A loose pattern like site-* would also match the archives of another job named site-old.
  • Delete only after the new backup has been created and verified, so a failing job never removes the last good copy.
  • Never let an empty variable turn the pattern into something like /*.tar.gz.

Making Backups Safe to Automate

A script that runs every night from a scheduler such as cron (lesson 170) has no one watching it, so it must protect itself:

  • Write to a temporary name, then rename. If the job is interrupted, a half-written .partial file is never mistaken for a finished backup. mv within one file system is atomic: the archive appears under its final name all at once.
  • Clean up on failure with an EXIT trap (lesson 124).
  • Check free space before starting.
  • Use a restrictive umask. umask 077 makes new archives readable only by their owner; a backup of private data must not be readable by everyone.
  • Refuse dangerous combinations, such as a destination inside the source folder, which would make each backup contain the previous ones.
  • Log with timestamps to standard output and errors to standard error, so cron or a log file captures what happened.
  • Prevent overlapping runs with a lock (lesson 171) when a job could run longer than its interval.
  • Exit with a meaningful status, so a monitoring system or a notification step (lesson 173) can report failures.

A Complete Example: A Backup Script

backup.sh creates a timestamped, compressed, verified archive of one folder, writes a checksum file next to it and keeps a configurable number of archives. It supports a dry run.

#!/usr/bin/env bash
#
# backup.sh - create a timestamped, verified .tar.gz backup and prune old ones
#
# Usage: backup.sh [-n] [-k KEEP] NAME SOURCE_DIR DEST_DIR
#   -n        dry run: report what would happen, change nothing
#   -k KEEP   number of NAME archives to keep in DEST_DIR (default: 7)
#
# Creates DEST_DIR/NAME-YYYYmmdd-HHMMSS.tar.gz and a matching .sha256 file.
# Exit status: 0 success, 1 failure, 2 bad usage.

set -euo pipefail
umask 077                      # archives may contain private data

readonly DEFAULT_KEEP=7
readonly EXCLUDES=(            # never worth backing up
  --exclude='*.tmp'
  --exclude='cache'
  --exclude='.git'
)

dry_run=0
keep=$DEFAULT_KEEP
partial=''                     # archive being written; removed on failure
trap '[[ -n $partial ]] && rm -f -- "$partial"' EXIT

log()   { printf '%s %s\n' "$(date '+%F %T')" "$*"; }
die()   { log "ERROR: $*" >&2; exit 1; }
usage() { echo "usage: ${0##*/} [-n] [-k KEEP] NAME SOURCE_DIR DEST_DIR" >&2; exit 2; }

parse_args() {
  local opt
  while getopts ':nk:' opt; do
    case $opt in
      n) dry_run=1 ;;
      k) keep=$OPTARG ;;
      *) usage ;;
    esac
  done
  shift $((OPTIND - 1))
  (( $# == 3 )) || usage
  name=$1 src=$2 dest=$3

  [[ $name =~ ^[A-Za-z0-9_-]+$ ]] || die "invalid NAME: ${name@Q}"
  [[ $keep =~ ^[0-9]+$ ]] && (( 10#$keep >= 1 )) || die "KEEP must be 1 or more: ${keep@Q}"
  keep=$((10#$keep))
}

check_paths() {
  local real
  real=$(realpath -e -- "$src" 2>/dev/null) || die "source not found: $src"
  src=$real
  [[ -d $src ]] || die "source is not a folder: $src"
  [[ $src != / ]] || die 'refusing to back up /'
  dest=$(realpath -m -- "$dest")
  [[ $dest/ != "$src"/* ]] || die "DEST_DIR must not be inside SOURCE_DIR: $dest"
  (( dry_run )) || mkdir -p -- "$dest"
}

check_space() {
  local needed avail probe=$dest
  needed=$(du -sb -- "$src" | cut -f1)              # uncompressed size: a safe upper bound
  while [[ ! -d $probe ]]; do probe=$(dirname -- "$probe"); done   # dry run: DEST may not exist yet
  avail=$(df --output=avail -B1 -- "$probe" | tail -n 1)
  log "source $src: $needed bytes; free at destination: $avail bytes"
  (( avail > needed )) || die "not enough free space in $dest"
}

create_archive() {
  local stamp archive rc=0 entries
  stamp=$(date +%Y%m%d-%H%M%S)
  archive=$dest/$name-$stamp.tar.gz
  [[ ! -e $archive ]] || die "archive already exists (two runs in one second?): $archive"

  if (( dry_run )); then
    log "dry run: would create $archive"
    return
  fi

  partial=$archive.partial
  tar -czf "$partial" -C "$(dirname -- "$src")" "${EXCLUDES[@]}" -- "$(basename -- "$src")" || rc=$?
  case $rc in
    0) ;;
    1) log 'WARNING: some files changed while they were being read' ;;
    *) die "tar failed with status $rc" ;;
  esac

  entries=$(tar -tzf "$partial" | wc -l) || die "archive failed verification: $partial"
  mv -- "$partial" "$archive"
  partial=''
  ( cd -- "$dest" && sha256sum -- "${archive##*/}" > "${archive##*/}.sha256" )
  log "created $archive ($entries entries, $(stat -c %s -- "$archive") bytes)"
}

prune_old() {
  local -a archives=()
  local f old
  shopt -s nullglob
  for f in "$dest/$name"-*.tar.gz; do              # glob results are sorted, so oldest first
    # exact match only: NAME "site" must not match archives of NAME "site-2025"
    [[ ${f##*/} =~ ^$name-[0-9]{8}-[0-9]{6}\.tar\.gz$ ]] && archives+=("$f")
  done
  shopt -u nullglob
  (( ${#archives[@]} > keep )) || { log "keeping all ${#archives[@]} archive(s) of $name"; return; }

  for old in "${archives[@]:0:${#archives[@]} - keep}"; do
    if (( dry_run )); then
      log "dry run: would remove $old"
    else
      rm -f -- "$old" "$old.sha256"
      log "removed $old"
    fi
  done
}

main() {
  parse_args "$@"
  check_paths
  check_space
  create_archive
  prune_old
}

main "$@"

How It Works

  • Arguments. NAME labels the backup job and becomes part of every archive name, so it is restricted to letters, digits, _ and -; that also makes it safe to use inside the retention regular expression. KEEP must be a whole number of at least 1; 10# reads it as decimal even with leading zeros.
  • Paths. The source is resolved with realpath -e and must be an existing folder other than /. The destination is resolved with realpath -m, because it may not exist yet, and must not be inside the source. Only after both checks pass is the destination created; a dry run never creates it.
  • Free space. du -sb measures the source in bytes, which is more than the compressed archive will need, and df --output=avail -B1 reports the free bytes at the destination. In a dry run the destination may not exist, so the loop walks up to the nearest existing parent folder.
  • Creating the archive. tar writes to NAME-STAMP.tar.gz.partial with the archive paths relative to the source's parent folder. || rc=$? captures tar's status without triggering set -e, and the case treats status 1 as a warning and anything higher as a failure. If the script stops for any reason, the EXIT trap removes the partial file.
  • Verifying. tar -tzf reads the whole archive; with pipefail, a failure there fails the command substitution and stops the script before the archive is accepted. Only then is the file renamed to its final name and its checksum written.
  • Retention. The loop collects only file names that match exactly NAME- + 8 digits + - + 6 digits + .tar.gz. Glob results are sorted, and the timestamp format sorts by date, so the oldest archives come first. Everything except the newest KEEP is removed with its checksum file, and only after the new archive exists.

Bugs Found While Testing

Three problems in the first version of this script were found by testing the error cases, and the fixes are part of the script above:

  • The first check_paths wrote the result of realpath straight into src. When the source did not exist, the failed command substitution set src to an empty string before die used it, so the message read source not found: with no name. Writing the result to a separate variable real keeps the original text for the message.
  • The first version created the destination folder before checking whether it was inside the source, so a refused run still left an empty backups folder inside the site. The check now comes first.
  • The first retention pattern, "$dest/$name"-[0-9]*-[0-9]*.tar.gz, also matched the archives of a job named site-2025 when pruning the job site, because [0-9]* matches any text that begins with a digit. The exact regular expression fixed it; in a test with both jobs writing to one folder, pruning site down to one archive left both site-2025 archives untouched.

Running the Complete Example

A dry run reports what would happen without creating the destination:

backup.sh -n site site /srv/vault; echo "status $?"
2026-11-24 11:01:20 source /srv/t164/site: 48 bytes; free at destination: 32212647936 bytes
2026-11-24 11:01:20 dry run: would create /srv/vault/site-20261124-110120.tar.gz
2026-11-24 11:01:20 keeping all 0 archive(s) of site
status 0

Three real runs, one second apart, keeping two archives:

backup.sh -k 2 site site /srv/vault; echo "status $?"   # run three times
ls -l /srv/vault
(cd /srv/vault && sha256sum -c ./*.sha256)
2026-11-24 11:01:20 source /srv/t164/site: 48 bytes; free at destination: 32212643840 bytes
2026-11-24 11:01:20 created /srv/vault/site-20261124-110120.tar.gz (7 entries, 299 bytes)
2026-11-24 11:01:20 keeping all 1 archive(s) of site
status 0
2026-11-24 11:01:21 source /srv/t164/site: 48 bytes; free at destination: 32212635648 bytes
2026-11-24 11:01:21 created /srv/vault/site-20261124-110121.tar.gz (7 entries, 299 bytes)
2026-11-24 11:01:21 keeping all 2 archive(s) of site
status 0
2026-11-24 11:01:22 source /srv/t164/site: 48 bytes; free at destination: 32212627456 bytes
2026-11-24 11:01:22 created /srv/vault/site-20261124-110122.tar.gz (7 entries, 299 bytes)
2026-11-24 11:01:22 removed /srv/vault/site-20261124-110120.tar.gz
status 0
total 16
-rw------- 1 root root 299 Nov 24 11:01 site-20261124-110121.tar.gz
-rw------- 1 root root  94 Nov 24 11:01 site-20261124-110121.tar.gz.sha256
-rw------- 1 root root 299 Nov 24 11:01 site-20261124-110122.tar.gz
-rw------- 1 root root  94 Nov 24 11:01 site-20261124-110122.tar.gz.sha256
site-20261124-110121.tar.gz: OK
site-20261124-110122.tar.gz: OK

The third run removed the oldest archive, both remaining archives pass their checksum test, and umask 077 made every file readable only by its owner (-rw-------). Each archive has 7 entries because the cache folder and the .git folder in the site were excluded.

Restoring the newest archive into an empty folder and comparing it with the source shows that the backup is usable:

mkdir -p restore-test
tar -xzf /srv/vault/site-20261124-110122.tar.gz -C restore-test
diff -r --exclude=cache --exclude=.git site restore-test/site && echo "restore matches source (except excluded folders)"
restore matches source (except excluded folders)

Invalid input and dangerous combinations are refused (timestamps shortened to TIME):

$ backup.sh site site site/backups
TIME ERROR: DEST_DIR must not be inside SOURCE_DIR: /srv/t164/site/backups
status 1
$ backup.sh site missing vault
TIME ERROR: source not found: missing
status 1
$ backup.sh my.site site vault
TIME ERROR: invalid NAME: 'my.site'
status 1
$ backup.sh -k 0 site site vault
TIME ERROR: KEEP must be 1 or more: '0'
status 1
$ backup.sh site / vault
TIME ERROR: refusing to back up /
status 1
$ backup.sh site site
usage: backup.sh [-n] [-k KEEP] NAME SOURCE_DIR DEST_DIR
status 2

Finally, a failure in the middle of the backup leaves nothing behind. Run as the unprivileged user nobody, with one file in the source made unreadable, tar fails with status 2:

TIME source /srv/t164/np/site: 48 bytes; free at destination: 32212783104 bytes
tar: site/app.conf: Cannot open: Permission denied
tar: Exiting with failure status due to previous errors
TIME ERROR: tar failed with status 2

The script exited with status 1 and the destination folder was empty afterwards: the EXIT trap removed the .partial file, so no incomplete archive could be mistaken for a good one. To run this script every night, schedule it with cron (lesson 170), for example 30 2 * * * /usr/local/bin/backup.sh site /srv/www/site /srv/backups >> /var/log/backup-site.log 2>&1, and copy the finished archives and their .sha256 files to a second location.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Automating Backups with Bash and get answers drawn from it.

Signed-in readers only.