Bookmark this page

Guided Exercise: Running Commands More Efficiently Using Loops

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
  1. Use the ssh and hostname commands to print the host name of servera and serverb to standard output.

    [student@workstation ~]$ ssh student@servera hostname
    servera.lab.example.com
    [student@workstation ~]$ ssh student@serverb hostname
    serverb.lab.example.com
    
  2. Create a for loop to perform the same task more efficiently.

    [student@workstation ~]$ for HOST in servera serverb
    do
    ssh student@${HOST} hostname
    done
    servera.lab.example.com
    serverb.lab.example.com
    
  3. Create a shell script to execute the same for loop.

    1. Create the /home/student/bin directory to contain the shell script.

      [student@workstation ~]$ mkdir ~/bin
    2. 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
      
    3. 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
      
    4. Ensure the newly created script is executable.

      [student@workstation ~]$ chmod +x ~/bin/printhostname.sh
    5. Run the script from your home directory.

      [student@workstation ~]$ printhostname.sh
      servera.lab.example.com
      serverb.lab.example.com
      
    6. Verify that the exit code of your script is 0.

      [student@workstation ~]$ echo $?
      0
      

Finish

On workstation, run the lab console-commands finish script to finish this exercise.

[student@workstation ~]$ lab console-commands finish

This concludes the guided exercise.

Revision: rh134-8.2-f0a9756