Skip to content

Practice Exercise: Exploring Bash Scripting Constructs

Objectives

  • Explore advanced Bash scripting constructs.
  • Understand how to work with arrays, strings, and files in Bash.
  • Create Bash scripts that use constructs for more complex tasks.

Scenario

Bash scripting offers a wide range of constructs for handling various tasks efficiently. In this exercise, you'll dive into more advanced Bash scripting constructs, including arrays, strings, and file operations, to perform complex tasks and solve real-world problems.

Tasks

Task 1: Working with Arrays

  • Create a Bash script named arrays.sh.
  • Declare an array of fruits and populate it with at least five fruit names.
  • Use a for loop to iterate through the array and display each fruit's name.
  • Implement logic to count and display the number of fruits in the array.
  • Comment your script to explain array usage.
    #!/bin/bash
    
    # Declare an array of fruits
    fruits=("Apple" "Banana" "Cherry" "Date" "Fig")
    
    # Display each fruit's name
    echo "List of fruits:"
    for fruit in "${fruits[@]}"; do
        echo "$fruit"
    done
    
    # Count and display the number of fruits in the array
    num_fruits=${#fruits[@]}
    echo "Total number of fruits: $num_fruits"
    
  • To run and test the script
    [intern@intern-a1t-inf-lnx1 ~]$ chmod +x arrays.sh
    [intern@intern-a1t-inf-lnx1 ~]$ ./arrays.sh
    List of fruits:
    Apple
    Banana
    Cherry
    Date
    Fig
    Total number of fruits: 5
    

Task 2: String Manipulation

  • Create a Bash script named strings.sh.
  • Declare a string variable with your name.
  • Use string manipulation to:
  • Print the length of your name.
  • Extract the first three characters of your name.
  • Convert your name to uppercase.
  • Display the results of each operation.
  • Comment your script to explain string manipulation.
    #!/bin/bash
    
    # Declare a string variable with your name
    name="intern"
    
    # Print the length of your name
    length=${#name}
    echo "Length of your name: $length"
    
    # Extract the first three characters of your name
    first_three="${name:0:3}"
    echo "First three characters of your name: $first_three"
    
    # Convert your name to uppercase
    uppercase_name=$(echo "$name" | tr '[:lower:]' '[:upper:]')
    echo "Your name in uppercase: $uppercase_name"
    
  • To run and test your script
    [intern@intern-a1t-inf-lnx1 ~]$ chmod +x strings.sh
    [intern@intern-a1t-inf-lnx1 ~]$ ./strings.sh
    Length of your name: 6
    First three characters of your name: jer
    Your name in uppercase: JEROME
    

Task 3: File Operations

  • Create a Bash script named file_operations.sh.
  • Use conditional statements to check if a file named sample.txt exists in the current directory.
  • If it exists, append a new line with a timestamp to the file; otherwise, create the file and write a message with a timestamp.
  • Implement error handling to display appropriate messages.
  • Comment your script to explain file operations.
    #!/bin/bash
    
    # Define the file name
    file="sample.txt"
    
    # Check if the file exists
    if [ -e "$file" ]; then
        # File exists, so append a new line with a timestamp
        timestamp=$(date '+%Y-%m-%d %H:%M:%S')
        echo "Appending timestamp to $file: $timestamp"
        echo "$timestamp" >> "$file"
    else
        # File doesn't exist, so create it and write a message with a timestamp
        timestamp=$(date '+%Y-%m-%d %H:%M:%S')
        echo "Creating $file and writing timestamp: $timestamp"
        echo "$timestamp" > "$file"
    fi
    
  • To run and test the script
    [intern@intern-a1t-inf-lnx1 ~]$ chmod +x file_operations.sh
    
    # sample.txt file exists
    [intern@intern-a1t-inf-lnx1 ~]$ ls -l sample.txt
    -rw-r--r--  1 intern  intern  160 Sep 20 05:23 sample.txt
    
    [intern@intern-a1t-inf-lnx1 ~]$ ./file_operations.sh
    Appending timestamp to sample.txt: 2023-09-20 05:24:55
    
    [intern@intern-a1t-inf-lnx1 ~]$ ls -l sample.txt
    -rw-r--r--  1 intern  intern  180 Sep 20 05:24 sample.txt
    
    # Removing existing sample.txt and rerunning script
    [intern@intern-a1t-inf-lnx1 ~]$ rm sample.txt
    [intern@intern-a1t-inf-lnx1 ~]$ ls -l sample.txt
    ls: sample.txt: No such file or directory
    [intern@intern-a1t-inf-lnx1 ~]$ ./file_operations.sh
    Creating sample.txt and writing timestamp: 2023-09-20 05:25:26
    

Task 4: Combining Constructs

  • Create a Bash script named complex_constructs.sh.
  • Combine arrays, strings, and file operations to solve a task:
  • Declare an array of names.
  • Use a loop to iterate through the array and:
    • Display a greeting message for each name.
    • Check if a file with the name exists in the current directory. If it does, append a message to that file; otherwise, create the file.
  • Comment your script to explain how constructs are used together.
    #!/bin/bash
    
    # Declare an array of names
    names=("Alice" "Bob" "Charlie" "David" "Eve")
    
    # Loop through the array
    for name in "${names[@]}"; do
        echo "Hello, $name!"
    
        # Define the filename based on the name
        filename="${name}_file.txt"
    
        # Check if the file exists
        if [ -e "$filename" ]; then
            # File exists, so append a message
            echo "Appending a message to $filename"
            echo "This is a message for $name." >> "$filename"
        else
            # File doesn't exist, so create it and write a message
            echo "Creating $filename and writing a message"
            echo "This is a message for $name." > "$filename"
        fi
    done
    
  • To run and test your code
    [intern@intern-a1t-inf-lnx1 ~]$ chmod +x complex_construct.sh
    [intern@intern-a1t-inf-lnx1 ~]$ ./complex_construct.sh
    Hello, Alice!
    Creating Alice_file.txt and writing a message
    Hello, Bob!
    Creating Bob_file.txt and writing a message
    Hello, Charlie!
    Creating Charlie_file.txt and writing a message
    Hello, David!
    Creating David_file.txt and writing a message
    Hello, Eve!
    Creating Eve_file.txt and writing a message
    

Conclusion

In this exercise, you've explored advanced Bash scripting constructs, including arrays, strings, and file operations. You've combined these constructs to perform more complex tasks and solve real-world problems. Understanding these Bash scripting elements is crucial for creating versatile and efficient scripts in a Linux environment.