Files
SysAdminAutomation/backup.sh
jcoffey-dev 5d417f3c4c Change the copyright holder to Coffey Labs
The scripts were attributed to LINUXexpert.org, which is being retired as a
site and is no longer where this work lives. Coffey Labs is the organisation
these projects belong to.

One line per script, fifteen of them, and nothing else. LICENSE is deliberately
untouched: its "Copyright (C) <year> <name of author>" lines are GPL boilerplate
showing you how to write your own notice, and the Free Software Foundation's
own copyright on the licence text is not ours to edit.

Both git contributors are the same person, so there is no third-party copyright
here that could not be restated.
2026-08-30 01:26:45 -07:00

64 lines
2.1 KiB
Bash

#!/bin/bash
# backup.sh - Backup directory to compressed tar archive
#
# Copyright (C) 2025 Coffey Labs
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <https://www.gnu.org/licenses/>.
#
# Usage: backup.sh <source_directory> <destination_directory>
# Description: Creates a tar.gz archive of the source directory in the destination.
set -euo pipefail
SRC="${1:-}"
DEST="${2:-}"
if [ -z "$SRC" ] || [ -z "$DEST" ]; then
echo "Usage: $0 <source_directory> <destination_directory>"
exit 1
fi
if [ ! -d "$SRC" ]; then
echo "Source directory '$SRC' not found!"; exit 1
fi
if [ ! -d "$DEST" ]; then
# create destination dir if it doesn't exist
mkdir -p "$DEST" || { echo "Failed to create destination '$DEST'"; exit 1; }
fi
base_name="$(basename "$SRC")"
# Seconds, not just the date. The old %Y%m%d name meant a second run on
# the same day silently overwrote the first -- losing a good backup at
# the exact moment someone was trying to take another one.
date_str="$(date +%Y%m%d-%H%M%S)"
archive_name="${base_name}-backup-${date_str}.tar.gz"
archive_path="$DEST/$archive_name"
if [ -e "$archive_path" ]; then
echo "Refusing to overwrite existing archive: $archive_path"
exit 1
fi
# Write to a partial name and rename only on success, so an interrupted
# run cannot leave a truncated file sitting there looking like a backup.
tmp_path="${archive_path}.partial"
trap 'rm -f -- "$tmp_path"' EXIT
if tar -czf "$tmp_path" -C "$(dirname "$SRC")" "$base_name"; then
mv -- "$tmp_path" "$archive_path"
trap - EXIT
echo "Backup successful: $archive_path"
ls -lh -- "$archive_path"
else
echo "Backup failed for $SRC" >&2
exit 1
fi