Skip to content

Practice Exercise: Exploring Bash Looping Constructs

Objectives

  • Learn about different looping constructs in Bash, including for and while loops.
  • Practice using loops to automate repetitive tasks in Bash scripts.
  • Create Bash scripts that incorporate for and while loops for various scenarios.

Scenario

Bash provides powerful looping constructs that allow you to automate tasks by repeating a series of commands. In this exercise, you'll explore different looping constructs, including for and while loops, and practice using them to solve real-world problems in Bash scripting.

Tasks

Task 1: Simple for Loop

  • Create a Bash script named simple_for_loop.sh.
  • Implement a simple for loop that:
  • Iterates through the numbers 1 to 5.
  • Prints each number to the console.
  • Test your script to ensure the for loop correctly prints the numbers.
    #!/bin/bash
    
    # Use a for loop to iterate through the numbers 1 to 5
    for number in {1..5}
    do
      echo "Number: $number"
    done
    

Task 2: for Loop with Array

  • Create a Bash script named for_loop_with_array.sh.
  • Declare an array of your favorite fruits.
  • Implement a for loop that:
  • Iterates through the elements of the array.
  • Prints a message for each fruit, such as "I like !".
  • Test your script to verify that it displays messages for each fruit.
    #!/bin/bash
    
    # Declare an array of favorite fruits
    fruits=("Apple" "Banana" "Orange" "Strawberry" "Mango")
    
    # Use a for loop to iterate through the array and print messages
    for fruit in "${fruits[@]}"
    do
      echo "I like $fruit!"
    done
    

Task 3: while Loop

  • Create a Bash script named while_loop.sh.
  • Implement a while loop that:
  • Asks the user to guess a secret number between 1 and 10.
  • Checks if the user's guess matches the secret number.
  • Provides feedback (e.g., "Too high," "Too low") until the user guesses correctly.
  • Exits the loop when the correct guess is made.
  • Include logic to generate a random secret number.
  • Test your script by playing the number guessing game.
  • Try implementing the guess.sh script on your own. If you get lost refer to the previous exercise

Task 4: Looping through Files

  • Create a Bash script named loop_through_files.sh.
  • Choose a directory with multiple files (e.g., text files).
  • Implement a for loop that:
  • Iterates through the files in the directory.
  • Performs an action on each file, such as counting lines or displaying its contents.
    #!/bin/bash
    
    # Specify the directory containing the files
    directory="/etc/selinux/"
    
    # Check if the directory exists
    if [ ! -d "$directory" ]; then
      echo "Directory not found: $directory"
      exit 1
    fi
    
    # Use a for loop to iterate through files in the directory
    for file in "$directory"/*; do
      # Check if the item is a file (not a directory)
      if [ -f "$file" ]; then
        echo "File: $file"
        # Display the contents of the file
        cat "$file"
        echo "=========================="
      fi
    done
    
  • Test your script by running it
    [intern@intern-a1t-inf-lnx1 ~]$ ./loop_through_files.sh
    File: /etc/openldap/ldap.conf
    #
    # LDAP Defaults
    #
    
    # See ldap.conf(5) for details
    # This file should be world readable but not world writable.
    
    #BASE   dc=example,dc=com
    #URI    ldap://ldap.example.com ldap://ldap-master.example.com:666
    
    #SIZELIMIT  12
    #TIMELIMIT  15
    #DEREF      never
    
    # When no CA certificates are specified the Shared System Certificates
    # are in use. In order to have these available along with the ones specified
    # by TLS_CACERTDIR one has to include them explicitly:
    #TLS_CACERT /etc/pki/tls/cert.pem
    
    # System-wide Crypto Policies provide up to date cipher suite which should
    # be used unless one needs a finer grinded selection of ciphers. Hence, the
    # PROFILE=SYSTEM value represents the default behavior which is in place
    # when no explicit setting is used. (see openssl-ciphers(1) for more info)
    #TLS_CIPHER_SUITE PROFILE=SYSTEM
    
    # Turning this off breaks GSSAPI used with krb5 when rdns = false
    SASL_NOCANON    on
    
    ==========================
    

Task 5: Advanced Looping

  • Create a Bash script named advanced_looping.sh.
  • Implement a more complex script that combines both for and while loops.
  • Use a for loop to iterate through a range of numbers (e.g., 1 to 3).
  • Inside the for loop, use a while loop to ask the user for input until they provide a valid response.
  • Handle different user inputs and provide feedback.
    #!/bin/bash
    
    # Iterate through a range of numbers using a for loop
    for i in {1..3}; do
      echo "Iteration $i"
    
      valid_input=false
    
      # Use a while loop to repeatedly ask for user input until valid
      while [ "$valid_input" = false ]; do
        read -p "Enter 'yes' or 'no': " user_input
    
        # Check if the input is either 'yes' or 'no'
        if [ "$user_input" = "yes" ]; then
          echo "You entered 'yes'."
          valid_input=true
        elif [ "$user_input" = "no" ]; then
          echo "You entered 'no'."
          valid_input=true
        else
          echo "Invalid input. Please enter 'yes' or 'no'."
        fi
      done
    
      echo "=========================="
    done
    
  • Test your script with various inputs to ensure it works as expected.
    [intern@intern-a1t-inf-lnx1 ~]$ chmod +x advanced_looping.sh
    [intern@intern-a1t-inf-lnx1 ~]$ ./advanced_looping.sh
    Iteration 1
    Enter 'yes' or 'no': yes
    You entered 'yes'.
    ==========================
    Iteration 2
    Enter 'yes' or 'no': no
    You entered 'no'.
    ==========================
    Iteration 3
    Enter 'yes' or 'no': yes
    You entered 'yes'.
    ==========================
    
    [intern@intern-a1t-inf-lnx1 ~]$ ./advanced_looping.sh
    Iteration 1
    Enter 'yes' or 'no': asdf
    Invalid input. Please enter 'yes' or 'no'.
    Enter 'yes' or 'no': yes
    You entered 'yes'.
    ==========================
    Iteration 2
    Enter 'yes' or 'no': asdfasfd
    Invalid input. Please enter 'yes' or 'no'.
    Enter 'yes' or 'no': no
    You entered 'no'.
    ==========================
    Iteration 3
    Enter 'yes' or 'no': adfsasdfyes
    Invalid input. Please enter 'yes' or 'no'.
    Enter 'yes' or 'no': yes
    You entered 'yes'.
    ==========================
    

Conclusion

In this exercise, you've explored different looping constructs in Bash, including for and while loops. You've practiced using loops to automate tasks and solve various problems in Bash scripting. Understanding how to implement looping constructs will enhance your ability to create efficient and versatile Bash scripts.