The Wayback Machine - https://web.archive.org/web/20241231050410/https://www.geeksforgeeks.org/case-command-in-linux-with-examples/
Open In App

case command in Linux with examples

Last Updated : 01 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The case command in Linux is an essential tool for simplifying script logic, especially when multiple if/elif conditions need to be evaluated for a single variable. It offers a more readable and efficient way to execute commands based on pattern matching, making your shell scripts easier to maintain and understand.

Here, we will better understand the case command in Linux, learning about its syntax, examples, and options.

Syntax

case WORD in [PATTERN [| PATTERN]...) COMMANDS ;;]... esac

where,

  • WORD: The variable or value that you want to match against different patterns.
  • PATTERN: One or more patterns to compare against the WORD. Each pattern is followed by commands to execute if the pattern matches.
  • COMMANDS: The commands to run when a specific pattern matches the WORD.
  • ;;: Ends the command block for each pattern.
  • esac: This marks the end of the case statement (it’s case spelled backward)

Basic Example

Basic Example

Common Option for the case Command

help case: Displays help information and details about the case command usage.help case

Conclusion

The case command is an adaptable and efficient alternative to if/elif when dealing with multiple conditional checks on a single variable. By using pattern matching, case allows for more readable and maintainable scripts, particularly when handling a wide variety of input conditions.

case command in Linux – FAQs

What is the primary use of the case command in Linux?

The case command is used for pattern matching in shell scripts. It allows you to evaluate a variable against multiple patterns and execute corresponding commands based on the match.

How is the case command different from if/elif?

The case command provides a more efficient and readable way to handle multiple conditions for a single variable, especially when dealing with numerous options. In contrast, if/elif checks conditions sequentially, which can make scripts harder to read and manage.

Can I use wildcards with the case command?

Yes, the case command supports wildcards such as *, ?, and character ranges like [], making it a powerful tool for handling various input patterns.

Is there a default case in the case command?

Yes, the * symbol serves as the default case in the case statement. It is executed when none of the defined patterns match the input.


Next Article

Similar Reads

three90RightbarBannerImg