Bash Project: Backup Script
A backup script is a script that copies files into a separate backup folder. It creates the folder, copies the files, and then checks that the copy is complete.
Copy files and list the result
The script creates the source and backup folders, then writes two files. Copying and listing in sorted order proves both files arrived.
mkdir -p data backup
printf 'first note\n' > data/a.txt
printf 'second note\n' > data/b.txt
cp data/*.txt backup/
ls backup | sortDry run prints the plan without copying
When the first argument is --dry-run, the script prints what it would copy. No backup folder is created and no file is copied.
mkdir -p data
printf 'first note\n' > data/a.txt
printf 'second note\n' > data/b.txt
if [ "${1:-}" = "--dry-run" ]; then
echo "would copy: data/a.txt"
echo "would copy: data/b.txt"
else
mkdir -p backup
cp data/*.txt backup/
fiRefuse a backup folder inside the source
The backup folder here sits inside the source folder, so copying would back up its own output. The guard prints a refusal and stops with a nonzero exit.
mkdir -p data
src="data"
dest="data/backup"
case "$dest" in
"$src"/*)
echo "refusing: backup folder is inside the source folder"
exit 1
;;
esac
mkdir -p "$dest"
cp "$src"/*.txt "$dest"/Example
mkdir -p data backup
printf 'first note\n' > data/a.txt
printf 'second note\n' > data/b.txt
printf 'third note\n' > data/c.txt
src="data"
dest="backup"
case "$dest" in
"$src"/*)
echo "refusing: backup folder is inside the source folder"
exit 1
;;
esac
cp "$src"/*.txt "$dest"/
ls "$dest" | sort
files=("$dest"/*.txt)
echo "files copied: ${#files[@]}"Key points
- mkdir -p: create a folder, and do nothing if it already exists.
- cp data/*.txt backup/: copy every text file from data into backup.
- ls backup | sort: list the copied files in a fixed order.
- --dry-run: a flag that prints what would happen without copying anything.
- Guard: a check that refuses to run when the backup folder sits inside the source.
- Verify after copying: list the files and count them before calling the job done.
In this example, the script creates the source and backup folders and writes three files. The guard checks whether the backup folder sits inside the source, and it does not, so the script goes on. Then cp copies the files, ls lists them in sorted order, and the array count prints how many files were copied.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Why refuse a backup folder inside the source folder?