Explain the `case` statement.

QuestionsQuestions4 SkillsProYour First Linux LabAug, 26 2025
0163

The case statement in shell scripting is a control structure that allows you to execute different blocks of code based on the value of a variable or expression. It is particularly useful for handling multiple conditions in a more organized and readable way compared to using multiple if statements.

Syntax:

case variable in
    pattern1)
        # Commands to execute if variable matches pattern1
        ;;
    pattern2)
        # Commands to execute if variable matches pattern2
        ;;
    ...
    *)
        # Commands to execute if no patterns match (default case)
        ;;
esac

Key Components:

  1. Variable: The variable or expression being evaluated.
  2. Patterns: Each pattern is checked against the value of the variable. If a match is found, the corresponding commands are executed.
  3. Commands: The commands that will run if the pattern matches.
  4. Double Semicolon (;;): This marks the end of each case block.
  5. Default Case (*): This is executed if none of the specified patterns match the variable's value.

Example:

Here’s a simple example of a case statement that checks the value of a variable:

#!/bin/bash

echo "Enter a number (1-3): "
read number

case $number in
    1)
        echo "You entered One."
        ;;
    2)
        echo "You entered Two."
        ;;
    3)
        echo "You entered Three."
        ;;
    *)
        echo "Invalid input. Please enter a number between 1 and 3."
        ;;
esac

Advantages:

  • Readability: The case statement makes the code cleaner and easier to read, especially when dealing with multiple conditions.
  • Efficiency: It can be more efficient than multiple if statements, as it evaluates the variable against patterns in a single structure.

Use Cases:

  • Menu selections
  • Command-line argument parsing
  • Handling different input types or values

The case statement is a powerful tool in shell scripting for managing multiple conditions effectively.

0 Comments

no data
Be the first to share your comment!