Fork me on GitHub

Project Notes

Bash Case Statements

How to use case statements in the bash shell.


The case statement (aka switch statements) is better suited to handling complex conditionals than nexted if conditions. They also support regular-expression style pattern matching

Formally, the case statement is as follows (although normally written with line breaks between cases and commands):


Points to note:

  • starts/ends with case/esac
  • ;; is required between cases. Unlike other languages, it cannot be omitted to allow control flow from one case to another
  • it branches to the first matching case. Later matches (if any) are ignored.
  • *) case is often used as a catch-all default - equivalent of an else condition.


See for various pattern matching options.

$ ./ 123
123 is: under 7*
$ ./ 888
888 is: like 7* or 8*
$ ./ 9
9 is: like 9*
$ ./ a
a is: a or b
$ ./ abc
abc is: abc
$ ./ def
def is: def
$ ./ left-hand
left-hand is: like *hand
$ ./
help is: (default)

The example demonstrates matching blank

$ ./ abc
abc is: defined option: abc
$ ./ ""
 is: blank option
$ ./ xyz
xyz is: (default)

Credits and References

About LCK#14 Bash
Project Source on GitHub Return to the Project Catalog

This page is a web-friendly rendering of my project notes shared in the LittleCodingKata GitHub repository.

LittleCodingKata is my collection of programming exercises, research and code toys broadly spanning things that relate to programming and software development (languages, frameworks and tools).

These range from the trivial to the complex and serious. Many are inspired by existing work and I'll note credits and references where applicable. The focus is quite scattered, as I variously work on things new and important in the moment, or go back to revisit things from the past.

This is primarily a personal collection for my own edification and learning, but anyone who stumbles by is welcome to borrow, steal or reference the work here. And if you spot errors or issues I'd really appreciate some feedback - create an issue, send me an email or even send a pull-request.