In this exercise, you will use loops to efficiently print the host name from multiple servers.
Outcomes
You should be able to create a for loop to iterate through a list of items from the command-line and in a shell script.
Log in as the student user on workstation using student as the password.
On workstation, run the lab console-commands start command.
The command runs a start script that determines if the servera and serverb hosts are reachable on the network.
The script will alert you if they are not available.
[student@workstation ~]$lab console-commands start
Use the ssh and hostname commands to print the host name of servera and serverb to standard output.
[student@workstation ~]$ssh student@servera hostnameservera.lab.example.com[student@workstation ~]$ssh student@serverb hostnameserverb.lab.example.com
Create a for loop to perform the same task more efficiently.
[student@workstation ~]$for HOST in servera serverb do ssh student@${HOST} hostname doneservera.lab.example.com serverb.lab.example.com
Create a shell script to execute the same for loop.
Create the /home/student/bin directory to contain the shell script.
[student@workstation ~]$mkdir ~/bin
Verify that the newly created directory is in your PATH environmental variable.
[student@workstation ~]$echo $PATH/home/student/.local/bin:/home/student/bin::/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin
Create a shell script at /home/student/bin/printhostname.sh to perform the for loop.
Use the cat command to verify the content of printhostname.sh.
[student@workstation ~]$vim ~/bin/printhostname.sh[student@workstation ~]$cat ~/bin/printhostname.sh#!/bin/bash #Execute for loop to print server hostname. for HOST in servera serverb do ssh student@${HOST} hostname done exit 0
Ensure the newly created script is executable.
[student@workstation ~]$chmod +x ~/bin/printhostname.sh
Run the script from your home directory.
[student@workstation ~]$printhostname.shservera.lab.example.com serverb.lab.example.com
Verify that the exit code of your script is 0.
[student@workstation ~]$echo $?0