KandZ – Tuts

We like to help…!

Linux CLI 63 🐧 case command in shell scripts

a - case command introduction
The case statement is used for conditional execution based on the value of a variable or expression.
It provides a more readable and compact alternative to multiple if-elif-else statements...
when you have a limited set of possible values to check against.
syntax

case variable in
pattern1)
commands if variable matches pattern1
;;
pattern2)
commands if variable matches pattern2
;;
pattern3)
commands if variable matches pattern3
;;
*)
commands if none of the above patterns match
;;
esac

1. variable is the value you want to check.
2. pattern1, pattern2, etc., are the values or patterns you want to match against.
3. ;; separates each pattern block.
4. * is a wildcard that matches any other case not explicitly listed.
example → 1. The case statement checks the value of the fruit variable against several patterns (apple, banana, orange).
2. If the fruit matches one of these patterns, the corresponding block of commands is executed.
3. If none of the patterns match, the * pattern's block of commands is executed.

b - case command and patterns
common types of patterns you can use with the case statement:
1. Simple Strings
2. Wildcards:
Use * to match any sequence of characters
Use ? to match any single character
3. Character Classes:
Use [...] to match any single character within a specified set
Use [^...] to match any single character not within the specified set.
some character classes → [[:upper:]], [[:lower:]], [[:alpha:]], [[:digit:]], [[:graph:]], [[:space:]] and [[:xdigit:]]
4. Alternatives: Use | to specify multiple possible patterns.
5. Default Pattern: The * pattern acts as the default, catching any value that doesn't match the previous patterns.

Leave a Reply