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
  1. 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.sh

    Start with the hashbang and a line that proves the script ran.

    #!/bin/bash
    echo "Starting $0"
  2. Make it executable

    chmod a+x backup_auditor.sh
    ./backup_auditor.sh
  3. 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
  4. Report the regular files

    Replace the bare echo with a test, so each path produces one message rather than two. -f is true when the path exists and is a regular file.

    vim backup_auditor.sh
    for item in /etc/skel /etc/passwd /srv/nightly-backup; do
        if [[ -f "$item" ]]; then
            echo "$item is a file"
        fi
    done
    ./backup_auditor.sh

    Only one path is reported. The other two produce no message at all, which does not yet meet the requirement.

  5. Add branches for directories and everything else

    Add the elif first. It is reached only when the test above it failed.

    vim backup_auditor.sh
        if [[ -f "$item" ]]; then
            echo "$item is a file"
        elif [[ -d "$item" ]]; then
            echo "$item is a directory"
        fi
    ./backup_auditor.sh

    Two paths report now, but the one that no longer exists is still silent. Add an else to catch whatever is left.

    vim backup_auditor.sh
        elif [[ -d "$item" ]]; then
            echo "$item is a directory"
        else
            echo "$item is neither a file nor a directory"
        fi
    cat backup_auditor.sh
    ./backup_auditor.sh

    Every 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
  6. Clean up

    Remove the script.

    rm ~/scripts/backup_auditor.sh
    cd ~