Using case statements

Rather than using multiple elif statements, a case statement may provide a simpler mechanism when evaluations are made on a single expression.

The basic layout of a case statement is listed below using pseudo-code:

case expression in
 case1) 
  statement1
  statement2
 ;;
 case2)
  statement1
  statement2
 ;;
 *)
  statement1
 ;;
esac

The statement layout that we see is not dissimilar to switch statements that exist in other languages. In bash, we can use the case statement to test for simple values, such as strings or integers. Case statements can cater for a side range of letters, such as [a-f] or a through to f, but they cannot easily deal with integer ranges such as [1-20].

The case statement will first expand the expression and then it will ...

Get Mastering Linux Shell Scripting now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.