Alternative to the Case Statement

Learn the cases when the associative array fits better than the case statement.

We'll cover the following

The case statement and an associative array solve a similar task. The array makes the relationship between data (key-value). The case statement does the same between data and commands (value-action).

Usually, it’s more convenient to handle data than code. Data is easier for modifying and checking for correctness. Therefore, it’s worth replacing the case statement with an associative array in some cases. Converting data into code is easy to do in Bash compared with other programming languages.

The following is an example of replacing a case statement with an array. Let’s suppose we want to write a wrapper script for the archiving utilities. It receives several command-line parameters. The first one defines if the script calls either the bsdtar or tar utility.

The following shows the script. It handles the command-line parameters in the case statement.

Get hands-on with 1400+ tech skills courses.