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
-
serveraandworkstation - Script location
-
~/scripts/collect_disk_data.sh - Output location
-
/tmp/disk-data/
-
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.shStart with the hashbang and a line that proves the script ran.
#!/bin/bash echo "Starting $0"Hand the file to
bashand it runs.bash collect_disk_data.sh -
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.shLook at
$0in the output. It changes fromcollect_disk_data.shto./collect_disk_data.sh, because$0reports how the script was invoked. -
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.shThe body runs once per host, and the loop ends when the list runs out.
-
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.txtNow move those commands into the loop, using
$hostin 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 -
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.shfor host in "$@"; doRead 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 -
Clean up
Remove the collected data and the script.
rm -rf /tmp/disk-data rm ~/scripts/collect_disk_data.sh cd ~