Exercise

Collecting Disk Data Exercise

Task

Write a script that collects disk information from every host named on the command line and stores each host's results in its own file.

Hosts
servera and workstation
Script location
~/scripts/collect_disk_data.sh
Output location
/tmp/disk-data/
  1. Create a basic script file

    Create the scripts directory, move into it, and open a new file.

    mkdir -p ~/scripts
    cd ~/scripts
    vim collect_disk_data.sh

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

    #!/bin/bash
    echo "Starting $0"

    Hand the file to bash and it runs.

    bash collect_disk_data.sh
  2. Make it executable

    Add the execute bit, then run the file itself rather than handing it to bash.

    chmod a+x collect_disk_data.sh
    ./collect_disk_data.sh

    Look at $0 in the output. It changes from collect_disk_data.sh to ./collect_disk_data.sh, because $0 reports how the script was invoked.

  3. Write a basic for loop

    Replace the announcement with a loop over a fixed list of hosts. Get the loop itself working before adding anything else to the body.

    vim collect_disk_data.sh
    #!/bin/bash
    echo "Starting $0"
    for host in workstation servera; do
        echo $host
    done
    ./collect_disk_data.sh

    The body runs once per host, and the loop ends when the list runs out.

  4. Iterate on the logic

    Get one host working by hand before putting the commands in the loop, so you know what they produce.

    mkdir -p /tmp/disk-data
    ssh student@servera lsblk > /tmp/disk-data/servera-disk-data.txt
    ssh student@servera df -h >> /tmp/disk-data/servera-disk-data.txt
    ls -l /tmp/disk-data
    cat /tmp/disk-data/servera-disk-data.txt

    Now move those commands into the loop, using $host in place of the fixed host name so the same three lines run for every item in the list.

    vim collect_disk_data.sh
    #!/bin/bash
    echo "Starting $0"
    for host in workstation servera; do
        echo $host > /tmp/disk-data/$host-disk-data.txt
        ssh student@$host lsblk >> /tmp/disk-data/$host-disk-data.txt
        ssh student@$host df -h >> /tmp/disk-data/$host-disk-data.txt
    done
    ./collect_disk_data.sh
    ls -l /tmp/disk-data
    cat /tmp/disk-data/workstation-disk-data.txt
  5. Make the script take arguments

    The host list is still hard coded, so the script can only ever inspect those two machines. Replace the list with "$@".

    vim collect_disk_data.sh
    for host in "$@"; do

    Read the whole script back, then clear the previous results and run it again, this time naming the hosts on the command line.

    cat collect_disk_data.sh
    rm -f /tmp/disk-data/*
    ./collect_disk_data.sh workstation servera
    ls -l /tmp/disk-data
    cat /tmp/disk-data/servera-disk-data.txt
  6. Clean up

    Remove the collected data and the script.

    rm -rf /tmp/disk-data
    rm ~/scripts/collect_disk_data.sh
    cd ~