Skip to content

Latest commit

 

History

History
108 lines (85 loc) · 2.32 KB

File metadata and controls

108 lines (85 loc) · 2.32 KB

Case Statements in Linux :

# Case Statements in Linux Shell Scripting

In Linux shell scripting, the `case` statement is a powerful tool for handling multiple conditions in a more readable and structured way. It provides an alternative to a series of `if-elif-else` statements when dealing with different values of a variable.

## 1. Basic Syntax

The basic syntax of a `case` statement in bash is as follows:

```bash
case variable in
    pattern1)
        # code to be executed if variable matches pattern1
        ;;
    pattern2)
        # code to be executed if variable matches pattern2
        ;;
    pattern3)
        # code to be executed if variable matches pattern3
        ;;
    *)
        # code to be executed if variable matches none of the patterns
        ;;
esac

2. Example Usage

2.1. Simple Case Statement

#!/bin/bash

fruit="apple"

case $fruit in
    "apple")
        echo "It's a delicious apple."
        ;;
    "orange")
        echo "It's a juicy orange."
        ;;
    "banana")
        echo "It's a ripe banana."
        ;;
    *)
        echo "Unknown fruit."
        ;;
esac

2.2. Case Statement with Pattern Ranges

#!/bin/bash

score=85

case $score in
    [90-100])
        echo "Excellent! You scored an A."
        ;;
    [80-89])
        echo "Good job! You scored a B."
        ;;
    [70-79])
        echo "Not bad. You scored a C."
        ;;
    *)
        echo "You need to improve."
        ;;
esac

2.3. Case Statement with Wildcards

#!/bin/bash

file="example.txt"

case $file in
    *.txt)
        echo "It's a text file."
        ;;
    *.pdf)
        echo "It's a PDF document."
        ;;
    *)
        echo "Unknown file type."
        ;;
esac

3. Notes

  • Each pattern should end with ;; to indicate the end of that particular case.
  • The *) at the end serves as the default case, similar to the else statement in if-elif-else constructs.
  • Use of square brackets allows for pattern matching using ranges or wildcards.

These examples illustrate the basic usage of case statements in Linux shell scripting. You can customize and expand upon these templates based on your specific requirements and use cases.



Next | Loops