A Backup Script with Arguments

Linux lab Intermediate 4 tasks 20 points

Write backup.sh, a script that copies a file you name into a backups folder, adding today's date to the copy's name. It should check its argument and report clearly whether it worked.

How it works: the terminal below is a real Linux machine running in your browser. Click it and type. Tasks tick themselves off as you complete them; questions are answered in the box under each task. Press Reset any time for a fresh machine. Your password on this machine (for sudo) is student.

student@vulntech:~ Starting…
Getting your Linux machine ready…
The first start downloads about 20 MB. After that your browser keeps it, and labs start in a moment.

Hints

Build it a step at a time: get the copy working first, then add the two checks at the top.

Quote "$1" everywhere, so names with spaces still work.

Solution explanation

The script checks its argument twice: -z "$1" catches a missing argument and prints the usage line, and ! -f "$1" catches a name that isn't a file. Both exit 1 so other programs can tell it failed. When the file is real, cp "$1" "backups/$1.$(date +%F)" makes the dated copy.

Show solution
cat <<'EOF' > backup.sh
#!/bin/bash
if [ -z "$1" ]; then
  echo "Usage: $0 FILE"
  exit 1
fi
if [ ! -f "$1" ]; then
  echo "$1 not found"
  exit 1
fi
cp "$1" "backups/$1.$(date +%F)"
echo "Backed up $1"
EOF
chmod +x backup.sh
./backup.sh
./backup.sh manifest.txt
./backup.sh nope.txt
ls backups
HOME LEARN COMMUNITY DASHBOARD