Makes a timestamped copy of a file next to the original before you edit or overwrite it. A one-line safety net for config files, scripts, or anything you're about to hand-edit.
#!/usr/bin/env bash
# Make a timestamped copy of a file: name.ext -> name.ext.20260816-153000.bak
# Usage: backup-file.sh <path>
set -euo pipefail
src="$1"
if [ ! -f "$src" ]; then
echo "not a file: $src" >&2
exit 1
fi
ts="$(date +%Y%m%d-%H%M%S)"
dest="${src}.${ts}.bak"
cp -p -- "$src" "$dest"
echo "$dest"
| path | string — positional argument, path to the file to back up, e.g. nginx.conf |
|---|
<path>.<timestamp>.bak (mode/timestamps preserved via cp -p)
and prints its path to stdout, exit 0. Exits 1 with a message on stderr if path
isn't a regular file.
$ ./backup-file.sh nginx.conf
nginx.conf.20260816-153000.bak
cp -p -- "$src" "$dest" uses -- and quoting so a filename starting with - can't be interpreted as a cp option.set -euo pipefail plus an explicit file-existence check means a missing/typo'd path fails clearly instead of silently doing nothing.