Exercise
Item Inspector Exercise
Task
A nightly backup job was given a list of paths to collect and some of them no longer look like what the job expects. Write a script that audits each path and reports it as a regular file, a directory, or neither. Every path must produce exactly one message.
- Host
servera- Script location
-
~/scripts/backup_auditor.sh
-
Create a basic script file
Create the scripts directory, move into it, and open a new file.
mkdir -p ~/scripts cd ~/scripts vim backup_auditor.shStart with the hashbang and a line that proves the script ran.
#!/bin/bash echo "Starting $0" -
Make it executable
chmod a+x backup_auditor.sh ./backup_auditor.sh -
Write a basic for loop
The backup list contains a directory, a regular file, and a path that no longer exists.
vim backup_auditor.sh#!/bin/bash echo "Starting $0" for item in /etc/skel /etc/passwd /srv/nightly-backup; do echo "$item" done./backup_auditor.sh -
Report the regular files
Replace the bare
echowith a test, so each path produces one message rather than two.-fis true when the path exists and is a regular file.vim backup_auditor.shfor item in /etc/skel /etc/passwd /srv/nightly-backup; do if [[ -f "$item" ]]; then echo "$item is a file" fi done./backup_auditor.shOnly one path is reported. The other two produce no message at all, which does not yet meet the requirement.
-
Add branches for directories and everything else
Add the
eliffirst. It is reached only when the test above it failed.vim backup_auditor.shif [[ -f "$item" ]]; then echo "$item is a file" elif [[ -d "$item" ]]; then echo "$item is a directory" fi./backup_auditor.shTwo paths report now, but the one that no longer exists is still silent. Add an
elseto catch whatever is left.vim backup_auditor.shelif [[ -d "$item" ]]; then echo "$item is a directory" else echo "$item is neither a file nor a directory" ficat backup_auditor.sh ./backup_auditor.shEvery path now produces exactly one message:
Starting ./backup_auditor.sh /etc/skel is a directory /etc/passwd is a file /srv/nightly-backup is neither a file nor a directory -
Clean up
Remove the script.
rm ~/scripts/backup_auditor.sh cd ~