5 Examples of Bash Case Statements

Try this guide with our instant dedicated server for as low as 40 Euros

bash case

Making decisions based on different conditions is a fundamental concept in almost all programming languages, including Bash scripting. 

Bash, being one of the most widely used shells in Linux environments, offers various structures to make such decisions. The Bash case statement is a powerful tool that executes specific command blocks based on pattern matching. 

In practical terms, a case statement is a more sophisticated version of the if-else statement blocks. You can use a cases statement block as an alternative to a long if-else block that checks multiple conditions.

In this tutorial, we will describe the basic syntax of the Bach case statement. Next, we will discuss five examples of using case statements in Bash scripts.

Table Of Content

  1. A Brief Overview of the Bash Case Statement
  2. 5 Bash Case Statement Examples
    1. The Prerequisites
    2. Example #1: Output a Description for Each Option
    3. Example #2: Multiple Patterns
    4. Example #3: Case Blocks inside For Loops
    5. Example #4: Create an Address Book
    6. Example #5: Check Input Character Case and Type
  3. Conclusion
  4. FAQs

A Brief Overview of the Bash Case Statement

The syntax of a Bash case statement is straightforward and resembles the if-elif-else blocks. However, you can use multiple patterns and actions in a much simpler syntax that is easy to read and implement. 

Here’s a simplified version of the Bach case syntax:

case evaluation expression in

  pattern1)

    commands;;

  pattern2)

    commands;;

  ...

  *)

    default commands;;

esac

Let’s look at the components of this syntax:

  • evaluation expression: The value that you want to match against the patterns.
  • pattern: A condition that the expression is matched against. If it matches, the command block following the pattern is executed.
  • commands: The block of commands that’s executed if the pattern matches the expression.
  • *): This is an optional default pattern that matches all conditions. This is the catch-all command block that is executed when no other pattern matches the evaluation condition.
  • esac: The end of the case statement, which is case spelled backward.

5 Bash Case Statement Examples

Now that you know the syntax of the Bash case statement, let’s see two examples that illustrate the versatility of the idea. But first, let’s check out the prerequisites.

The Prerequisites

Before diving into the case statement, there are a few prerequisites you should be familiar with:

  • A system running a mainstream distribution.
  • A user account with sudo privileges.
  • A basic understanding of Bash scripting and syntax.

Example #1: Output a Description for Each Option

A great use case of the Bash case statement is displaying a custom message or description against the user’s choice. Consider the following script:

#!/bin/bash

echo "Choose an option: A, B, or C"
read option

case $option in
  A)
    echo "Option A selected: Running full system scan.";;
  B)
    echo "Option B selected: Updating system software.";;
  C)
    echo "Option C selected: Checking system health.";;
  *)
    echo "Invalid option selected.";;
esac

Let’s break down this script to see how it works

  1. Script Initiation and User Prompt: The script begins by displaying a message, asking the user to choose one of three options: A, B, or C.
  2. User Input: It then waits for the user to enter their choice and stores this input in a variable named option.
  3. Decision Making:
      – If the user enters A, the script responds with a message Option A selected: Running full system scan.
      – If the user inputs B, the script responds with Option B selected: Updating system software.
      – For an input of C, it states Option C selected: Checking system health.
  4. Handling Invalid Input: If the user’s input does not match any of the valid options (A, B, or C), the script notifies the user with the Invalid option selected message.
  5. Script Conclusion: After executing the corresponding action based on the user’s choice, the script concludes its operation.

Example #2:  Multiple Patterns

In the previous example, the patterns have a single echo command that the script executed in response to the user input.

In most cases, the patterns in a case statement comprise multiple commands that can deal with complex real-world challenges. The following example script demonstrates the use of multiple options (separated by |) in the patterns so that the user can have more options or variability in input. 

#!/bin/bash

echo "Enter your favorite fruit: "
read fruit

case $fruit in
  apple|Apple)
    echo "Apple pie is delicious!";;
  banana|Banana)
    echo "Bananas are rich in potassium.";;
  *)
    echo "Sorry, I don't know about that fruit.";;
esac

This shell script follows a systematic process to interact with the user about their favorite fruit.

Let’s break down and see how this script works:

  1. Initial Prompt: The script starts by asking the user to enter their favorite fruit.
    2. User Response: The script captures the user’s input in a variable named fruit.
    3. Decision Logic:
      – If the user types apple or Apple, the script responds with Apple pie is delicious!
      – If banana or Banana is entered, it comments Bananas are rich in potassium.
      – For any other input, the script apologizes with Sorry, I don’t know about that fruit
    4. The End of Script: After responding based on the user’s input, the script concludes its execution.

Example-3-Multiple-Patterns

Example #3: Case Blocks inside For Loops

You can use case statements inside loops for more complex scripts. A great example of this syntax is processing multiple files based on their extension. Consider the following script that implements the core idea that you can extend for practical purposes:

#!/bin/bash

for file in *; do
  case $file in
    *.txt)
      echo "Processing text file: $file";;
    *.log)
      echo "Processing log file: $file";;
    *)
      echo "Skipping $file";;
  esac
done

This shell script systematically processes files in the current directory.

Here’s a breakdown of the script’s flow:

  1. Loop Through Files: The script starts by using the for loop to iterate over every file in the current directory.
  2. The File Type Check:
      – If a file ends with .txt, the script announces it’s processing a text file.
      – If a file has a .log extension, it indicates it’s processing a log file.
  3. Other Files: For files that don’t match the above criteria, it mentions it’s skipping them.
  4. End of Execution: The script repeats this process for each file in the directory until all files have been checked.

Case-Blocks-inside-For-Loops

Example #4: Create an Address Book

Let’s check a real-world utility that uses the case statement blocks. You can build a simple address book where users have the choice of actions like adding or viewing contacts. Here’s the sample script that sets up the menu and offers appropriate locations where you can add the processing functionalities.

#!/bin/bash

echo "Select an action: [A]dd, [V]iew, [Q]uit"
read action

case $action in
  A|a)
    echo "Enter contact name:"
    read name
    echo "$name added to the address book.";;
  V|v)
    echo "Displaying contacts...";;
  Q|q)
    echo "Exiting address book.";;
  *)
    echo "Invalid action.";;
esac

This shell script offers a simple menu for an address book with the following steps:

  1. User Prompt: The script begins by asking the user to select an action: Add, View, or Quit, represented by the letters A, V, and Q, respectively.
  2. User Selection: The script captures the user’s chosen action.
  3. Action Handling:
      – Add (A/a): If the user selects Add (either uppercase A or lowercase a), the script prompts for a contact name, captures it, and then displays a message confirming that the name has been added to the address book.
      – View (V/v): Choosing View (either V or v) triggers a message that contacts are being displayed.
      – Quit (Q/q): Selecting Quit (either Q or q) results in a message indicating that the script is exiting the address book.
  4. Invalid Input: If the user enters anything other than A, V, or Q, the script informs them that it’s an invalid action.
  5. The End of Script: The script concludes after executing the corresponding action for the user’s input.

Example 4 Create an Address Book

Example #5: Check Input Character Case and Type

The following script demonstrates how you can use a case statement to test the type and case (in the case of alphabets).

#!/bin/bash

echo "Enter a character:"
read char

case $char in
  [A-Z])
    echo "Uppercase letter.";;
  [a-z])
    echo "Lowercase letter.";;
  [0-9])
    echo "Digit.";;
  *)
    echo "Special character or invalid input.";;
esac

Here’s the breakdown of the script: 

  1. Prompt for Input: The script starts by asking the user to enter a single character.
  2. Capture the Character: The script reads and stores the entered character in a variable named char.
  3. Input Analysis:
      – If the character is an uppercase letter (A to Z), the script responds with Uppercase letter.
      – If it’s a lowercase letter (a to z), the script indicates Lowercase letter.
      – If the user enters a digit (0 to 9), the script identifies it as Digit.
  4. Other Inputs: For any other characters, such as special symbols or combinations of characters, the script reports Special character or invalid input.
  5. Script Completion: After analyzing the character and displaying the result, the script ends.

Example 5 Check Input Character Case and Type

Also Read: How to Read Files Line by Line in a Bash Script [5 Simple Methods Inside!]

Conclusion

The Bash case statement is an efficient and readable way to handle multiple conditions in your scripts. It simplifies decision-making processes and makes your scripts cleaner and more maintainable. Whether you’re a beginner or an experienced developer, mastering the case statement can significantly enhance your scripting skills.

As you continue to expand your Bash scripting capabilities, consider the infrastructure you’re working with. For those requiring robust and reliable hosting solutions, RedSwitches Bare Metal Hosting Provider offers a solid foundation for deploying your applications and scripts.

We offer the best dedicated server pricing and deliver instant dedicated servers, usually on the same day the order gets approved. Whether you need a dedicated server, a traffic-friendly 10Gbps dedicated server, or a powerful bare metal server, we are your trusted hosting partner.

FAQs

Q. What is a case statement in bash?

A case statement in bash is a construct that allows you to perform different actions based on the value of a variable. It is similar to a switch statement in other programming languages.

Q. How to use case statements in bash?

To use case statements in bash, you need to use the syntax: 

bash case expression in pattern1) command1;; pattern2) command2;; … patternN) commandN;; *) default_command;; esac 

Replace `expression` with the variable you want to check and `pattern1, pattern2, …, patternN` with the values you want to match. The `command1, command2, …, commandN` are the commands to be executed if the respective pattern matches. The `default_command` will be executed if none of the patterns match.

Q. What is the syntax for a case statement in bash?

The syntax for a case statement in bash is: “`bash case expression in pattern1) command1;; pattern2) command2;; … patternN) commandN;; *) default_command;; esac “` Where `expression` is the variable to be checked, `pattern1, pattern2, …, patternN` are the patterns to match, and `command1, command2, …, commandN` are the commands to be executed for the matching patterns. The `default_command` is executed if none of the patterns match.

Q. How do I terminate a command in a case statement in bash?

To terminate a command in a case statement in bash, you use `;;` (double semicolon). It is used to indicate the end of a command block for a specific pattern in the case statement.

Q. What is the exit status of a case statement in bash?

The exit status of a case statement in bash is the exit status of the last command that is executed within the block corresponding to the matched pattern. If no patterns match and the default command is executed, the exit status will be that of the default command.

Q. How does a case statement make it easier to maintain complex conditionals in bash?

A case statement makes it easier to maintain complex conditionals in bash by allowing you to organize multiple different choices into separate blocks. This makes the code more readable and maintainable compared to using multiple if-then-else statements.

Q. Can I have multiple patterns in each clause of a case statement in bash?

Yes, you can have multiple patterns in each clause of a case statement in bash. You can list multiple patterns separated by `|` (pipe) in a single clause, and the associated commands will be executed if any of the patterns match.

Q. What is the purpose of the -n flag in a case statement in bash?

The -n flag in a case statement in bash is used to check if the value of the expression is not empty (null). It is often used to validate user input or variable values before executing the corresponding commands in the case statement.

Q. How do I use the read command with a case statement in bash?

You can use the read command with a case statement in bash to prompt the user for input and then use the input value as the expression to be checked in the case statement. For example: “`bash read -p “Enter the name: ” name case $name in pattern1) command1;; pattern2) command2;; … patternN) commandN;; *) default_command;; esac “`

Q. What is the purpose of the shopt -s nocasematch command in a case statement in bash?

The purpose of the `shopt -s nocasematch` command in a case statement in bash is to enable case-insensitive pattern matching. When this option is set, patterns in the case statement will be matched without considering the case of letters, making it useful for scenarios where case sensitivity is not required.

Q. How can I use a case statement to handle file input and execute different commands based on the file type?

You can use a case statement in bash to handle file input by checking the filename extension or type and executing different commands based on the file type. For example: “`bash filename=”example.txt” case $filename in *.txt) echo “Processing text file” # Commands to process text file ;; *.pdf) echo “Processing PDF file” # Commands to process PDF file ;; *) echo “Unsupported file type” # Default command for unsupported file types ;; esac “`

Try this guide with our instant dedicated server for as low as 40 Euros