How to Use the "Case" Statement In Bash?

10 minutes read

In Bash scripting, the "case" statement provides a way to perform different actions based on the value of a variable or an expression. It allows you to compare the value against a set of patterns and execute corresponding commands for matching patterns.


The general syntax for using a "case" statement in Bash is:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
case expression in
  pattern1)
    commands1
    ;;
  pattern2)
    commands2
    ;;
  pattern3|pattern4)
    commands3
    ;;
  *)
    default_commands
    ;;
esac


Here's how it works:

  • The "case" keyword marks the beginning of the case statement.
  • The "expression" represents the value you want to compare. It can be a variable or an expression.
  • Each "pattern" is checked against the value of the expression, and if a pattern matches, the corresponding commands are executed.
  • After the commands for a pattern are executed, you must end them with double semicolons (";;") to mark the end of that pattern.
  • Multiple patterns can be combined using the pipe symbol ("|") to execute the same set of commands for multiple patterns.
  • The "*)" pattern is a wildcard that matches anything that didn't match the previous patterns. It is used for executing default commands when no other patterns match.
  • The "esac" keyword marks the end of the case statement.


Here's an example to illustrate the usage of the case statement:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
fruit="apple"
case $fruit in
  "apple"|"orange")
    echo "It's a delicious fruit!"
    ;;
  "banana")
    echo "It's a tropical fruit!"
    ;;
  *)
    echo "Unknown fruit."
    ;;
esac


In this example, if the value of the "fruit" variable is either "apple" or "orange", the script would output "It's a delicious fruit!". If the value is "banana", it would output "It's a tropical fruit!". Otherwise, if the value is anything else, it would output "Unknown fruit." as specified in the default wildcard pattern.


The case statement in Bash provides a flexible way to handle multiple conditions and perform different actions based on the matches.

Best Linux Books to Read in 2024

1
Linux Bible

Rating is 5 out of 5

Linux Bible

2
Practical Linux Forensics: A Guide for Digital Investigators

Rating is 4.9 out of 5

Practical Linux Forensics: A Guide for Digital Investigators

3
The Linux Command Line, 2nd Edition: A Complete Introduction

Rating is 4.8 out of 5

The Linux Command Line, 2nd Edition: A Complete Introduction

4
How Linux Works, 3rd Edition: What Every Superuser Should Know

Rating is 4.7 out of 5

How Linux Works, 3rd Edition: What Every Superuser Should Know

5
CompTIA Linux+ Certification All-in-One Exam Guide, Second Edition (Exam XK0-005)

Rating is 4.6 out of 5

CompTIA Linux+ Certification All-in-One Exam Guide, Second Edition (Exam XK0-005)

6
CompTIA Linux+ Study Guide: Exam XK0-005 (Sybex Study Guide)

Rating is 4.5 out of 5

CompTIA Linux+ Study Guide: Exam XK0-005 (Sybex Study Guide)


What is the role of the "!" operator in a "case" statement?

In a "case" statement, the "!" operator is used to negate a condition. It is primarily used in switch statements found in programming languages like C++, Java, and JavaScript.


When evaluating a case, the "!" operator applies a logical NOT operation on the condition. It converts a true condition into false and vice versa. This allows for more flexible evaluation of cases based on negated conditions.


For example, consider the following code snippet in JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
let language = "Python";

switch (language) {
  case "JavaScript":
    console.log("Awesome!");
    break;
  case "Python":
    console.log("Nice!");
    break;
  case "Java":
    console.log("Cool!");
    break;
  default:
    console.log("Unknown language!");
}


In this case statement, when language is "Python", the case "Python" is matched and executes its corresponding code block, printing "Nice!" to the console. If the "!" operator were used, like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
switch (language) {
  case "JavaScript":
    console.log("Awesome!");
    break;
  case !"Python":
    console.log("Nice!");
    break;
  case "Java":
    console.log("Cool!");
    break;
  default:
    console.log("Unknown language!");
}


Now, when language is "Python", the condition "Python" is negated to false using the "!" operator. As a result, the case with the negated condition is matched, and the code block associated with it is executed, printing "Nice!" to the console.


How to use complex conditions in a "case" statement?

To use complex conditions in a "case" statement, you can combine multiple conditions using logical operators such as "AND" and "OR". Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
DECLARE
    age INTEGER := 25;
    salary INTEGER := 50000;
    position VARCHAR2(50) := 'Manager';
BEGIN
    CASE
        WHEN age > 18 AND age <= 30 AND salary > 50000 THEN
            DBMS_OUTPUT.PUT_LINE('You are a young employee with a high salary.');
        WHEN age > 30 AND position = 'Manager' OR position = 'Director' THEN
            DBMS_OUTPUT.PUT_LINE('You are an experienced employee in a managerial position.');
        ELSE
            DBMS_OUTPUT.PUT_LINE('You have a different profile.');
    END CASE;
END;
/


In this example, we have defined variables for age, salary, and position. The "case" statement checks for different conditions using logical operators:

  • The first condition checks if the age is between 18 and 30 and the salary is greater than 50,000. If both conditions are true, it prints a message indicating that the employee is young with a high salary.
  • The second condition checks if the age is greater than 30 and the position is either "Manager" or "Director". If this condition is true, it prints a message indicating that the employee is experienced in a managerial position.
  • If none of the conditions above are met, it prints a default message indicating a different profile.


You can modify and add more complex conditions based on your requirements.


What is the scope of variables used within a "case" statement?

In most programming languages, the scope of variables used within a "case" statement is limited to the specific case block where the variable is declared.


A "case" statement, also known as a "switch" statement in some languages, is typically used to execute different code blocks based on the value of a variable or expression. Each case block represents a specific value or range of values that the variable can have.


When a particular case is matched, the code within that case block is executed. Variables declared within a case block are local to that block and can only be accessed within the scope of that specific case. They cannot be accessed outside the case block or in other case blocks.


Here's an example in the C programming language to illustrate the scope of variables within a "case" statement:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
switch (variable) {
    case 1:
        int x = 5;
        printf("x is %d\n", x);
        break;
    case 2:
        int y = 10;
        printf("y is %d\n", y);
        break;
    default:
        printf("Default case\n");
}


In this example, the variable "x" is only accessible within the case block for case 1, and the variable "y" is only accessible within the case block for case 2. The variables "x" and "y" cannot be accessed outside their respective case blocks.


It's important to note that different programming languages may have slight variations in how variables are scoped within a "case" statement, so it's always a good idea to refer to the specific language's documentation or syntax for accurate information.


How to match a single pattern in a "case" statement?

To match a single pattern in a "case" statement, you can use the "==" operator to compare the value being tested with a specific pattern. Here's an example in Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def match_pattern(value):
    case value:
        when 1:
            print("Pattern 1 matched")
        when 2:
            print("Pattern 2 matched")
        when 3:
            print("Pattern 3 matched")
        else:
            print("No pattern matched")

match_pattern(2)  # Output: Pattern 2 matched
match_pattern(4)  # Output: No pattern matched


In this example, the "value" parameter is compared against different patterns using the "when" keyword in the "case" statement. If a match is found, the corresponding block of code is executed. If none of the patterns match, the code inside the "else" block is executed.


What is the role of the "esac" keyword in a "case" statement?

The "esac" keyword is used to indicate the end of a "case" statement in a programming language like Bash. It is the reverse spelling of "case" and is used to close the block of code associated with the "case" statement. The "esac" keyword helps the interpreter or compiler understand the scope of the "case" statement and exit it properly.


What is the exit status of a "case" statement in Bash?

The exit status of a "case" statement in Bash is determined by the exit status of the last command executed within the selected code block. If the last command returns a zero exit status (i.e., success), the overall exit status of the "case" statement will be zero. If the last command returns a non-zero exit status (indicating an error or failure), the overall exit status of the "case" statement will be non-zero.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

The &#34;if-else&#34; statement in Bash allows you to create conditional logic in your scripts. It helps you to make decisions or perform specific actions based on certain conditions. Here is how you can use the &#34;if-else&#34; statement in Bash:Syntax: if c...
To write a basic Bash script, follow these steps:Open a text editor and create a new file with a .sh extension (e.g., script.sh).Start the script with a shebang, which tells the system to interpret the commands using Bash. Use &#34;#!/bin/bash&#34; at the begi...
In Bash, you can use the &#34;if then&#34; conditional statement to perform specific actions based on certain conditions. The syntax of the &#34;if then&#34; statement in Bash is as follows: if condition then # code to be executed if the condition is true el...
To redirect the output of a bash script to another file, you can use the &#34;&gt;&#34; symbol followed by the filename. Here&#39;s how to do it:Open the terminal and navigate to the directory where your bash script is located. Use the following syntax to redi...
Conditional statements in Bash scripts allow you to create branches in your code based on certain conditions. These statements check whether a particular condition is true or false and execute different sets of commands accordingly.The basic structure of a con...
To check if enable-bracketed-paste is enabled or disabled in Bash, you can use the following steps:Open the terminal or command prompt on your system.Type bash and hit Enter to launch the Bash shell.Enter bind -v | grep enable-bracketed-paste and press Enter.I...