Skip to content

Practice Exercise: Understanding Bash Scripting Syntax

Objectives

  • Learn and practice essential Bash scripting syntax.
  • Understand the structure of Bash scripts.
  • Create more complex Bash scripts using loops, conditionals, and functions.

Scenario

Bash scripting is a powerful tool for automating tasks on a Linux system. To become proficient, you need to understand the syntax and structure of Bash scripts. In this exercise, you'll dive deeper into Bash scripting syntax and create more complex scripts.

Tasks

Task 1: Using Variables

  • Create a Bash script named variables.sh.
  • Declare and assign values to different types of variables (string, integer, float).
  • Use echo to display the values of these variables.
  • Comment your script to explain variable usage.
    #!/bin/bash
    
    # This script demonstrates the use of variables and arrays in Bash.
    
    # String variable.
    name="John"
    
    # Integer variable.
    age=30
    
    # Float variable.
    salary=45000.50
    
    # Array variable.
    fruits=("Apple" "Banana" "Cherry")
    
    # Display the values of the variables.
    echo "Name: $name"
    echo "Age: $age"
    echo "Salary: $salary"
    
    # Access and display array elements.
    echo "Fruits: ${fruits[0]}, ${fruits[1]}, ${fruits[2]}"
    
  • To run the script
    [intern@intern-a1t-inf-lnx1 ~]$ chmod +x variable.sh
    [intern@intern-a1t-inf-lnx1 ~]$ ./variable.sh
    Name: John
    Age: 30
    Salary: 45000.50
    Fruits: Apple, Banana, Cherry
    

Task 3: Conditional Statements

  • Create a Bash script named conditional.sh.
  • Implement conditional statements (if-else) to perform different actions based on user input.
  • Prompt the user for a numeric value and check if it's positive or negative.
  • Display appropriate messages for each case.
    #!/bin/bash
    
    # This script demonstrates the use of conditional statements in Bash.
    
    # Prompt the user for a numeric value.
    read -p "Enter a number: " number
    
    # Check if the number is positive, negative, or zero.
    if [ $number -gt 0 ]; then
      echo "The number is positive."
    elif [ $number -lt 0 ]; then
      echo "The number is negative."
    else
      echo "The number is zero."
    fi
    
  • Test your script with various inputs.
    [intern@intern-a1t-inf-lnx1 ~]$ chmod +x conditional.sh
    [intern@intern-a1t-inf-lnx1 ~]$ ./conditional.sh
    Enter a number: 1
    The number is positive.
    [intern@intern-a1t-inf-lnx1 ~]$ ./conditional.sh
    Enter a number: -1
    The number is negative.
    [intern@intern-a1t-inf-lnx1 ~]$ ./conditional.sh
    Enter a number: 0
    The number is zero.
    

Task 4: Loops and Iteration

  • Create a Bash script named loop.sh.
  • Use a for loop to display numbers from 1 to 5.
  • Use a while loop to read user input until they enter 'q' to quit.
  • Comment your script to explain loop usage.
    #!/bin/bash
    
    for i in {1..5}; do
        echo "Number: $i"
    done
    
    while true :
    do
        read -r input
        if [ "$input" == "q" ]; then
            echo "Quitting the loop."
            break
        fi
        echo "You entered: $input"
    done
    
  • To run the script
    [intern@intern-a1t-inf-lnx1 ~]$ chmod +x loop.sh
    [intern@intern-a1t-inf-lnx1 ~]$ ./loop.sh       
    Number: 1
    Number: 2
    Number: 3
    Number: 4
    Number: 5
    asdf
    You entered: asdf
    q
    Quitting the loop.
    

Task 5: Functions

  • Create a Bash script named functions.sh.
  • Define a function that calculates the square of a number.
  • Call this function with different input values.
  • Comment your script to explain function usage.
    #!/bin/bash
    
    # This script demonstrates the use of functions in Bash.
    
    # Define a function to calculate the square of a number.
    calculate_square() {
      local number=$1
      local square=$((number * number))
      echo "The square of $number is $square."
    }
    
    # Call the function with different input values.
    calculate_square 5
    calculate_square 8
    calculate_square 12
    
    # You can also use variables to store and pass values to the function.
    num=3
    calculate_square $num
    
  • To run and test the script
    [intern@intern-a1t-inf-lnx1 ~]$ ./functions.sh
    The square of 5 is 25.
    The square of 8 is 64.
    The square of 12 is 144.
    The square of 3 is 9.
    

Task 6: Combining Syntax Elements

  • Create a Bash script named complex_script.sh.
  • Combine the syntax elements you've learned:
  • Declare variables.
  • Use conditional statements to check conditions.
  • Implement loops for iteration.
  • Define and call functions.
  • Create a script that calculates the factorial of a number using a loop or a recursive function.
  • Test your script with various numbers.
    #!/bin/bash
    
    # This script demonstrates combining various Bash syntax elements.
    
    # Function to calculate the factorial of a number recursively.
    calculate_factorial() {
      local num=$1
      if [ $num -le 1 ]; then
        echo 1
      else
        local prev_factorial=$(calculate_factorial $((num - 1)))
        echo $((num * prev_factorial))
      fi
    }
    
    # Prompt the user for a number.
    read -p "Enter a positive integer: " number
    
    # Check if the input is a positive integer.
    if [[ $number =~ ^[1-9][0-9]*$ ]]; then
      # Calculate the factorial of the number using the function.
      factorial=$(calculate_factorial $number)
      echo "The factorial of $number is $factorial."
    else
      echo "Invalid input. Please enter a positive integer."
    fi
    
  • To run and test the script
    [intern@intern-a1t-inf-lnx1 ~]$ chmod +x complex_script.sh
    [intern@intern-a1t-inf-lnx1 ~]$ ./complex_script.sh
    Enter a positive integer: 1
    The factorial of 1 is 1.
    [intern@intern-a1t-inf-lnx1 ~]$ ./complex_script.sh
    Enter a positive integer: 3
    The factorial of 3 is 6.
    [intern@intern-a1t-inf-lnx1 ~]$ ./complex_script.sh
    Enter a positive integer: 9
    The factorial of 9 is 362880.
    

Task 7: Script Execution and Documentation

  • Experiment with different ways to execute your Bash scripts:
  • Run a script by specifying the interpreter explicitly (e.g., bash script.sh).
  • Add your script to a directory in your PATH and execute it from any location.
  • Use a shebang (#!/bin/bash) at the script's beginning and make it executable to run it directly.
  • Let's use the complex_script.sh we created earlier.
  • And move it to one of our PATH
    [intern@intern-a1t-inf-lnx1 ~]$ echo $PATH
    /home/intern/.local/bin:/home/intern/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin
    
  • Let's move it to /usr/local/bin
    [intern@intern-a1t-inf-lnx1 ~]$ sudo mv complex_script.sh /usr/local/bin
    [intern@intern-a1t-inf-lnx1 ~]$ complex_script.sh
    Enter a positive integer: 1
    The factorial of 1 is 1.
    

Conclusion

In this exercise, you've delved into the syntax of Bash scripting, including variables, conditional statements, loops, and functions. You've created more complex scripts that combine these elements. Understanding Bash syntax is essential for creating efficient and powerful scripts to automate tasks in a Linux environment.