...

/

Alternative to the Case Statement

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.

 #!/bin/bash

utility="$1"

case "$utility" in
    "-b"|"--bsdtar")
        bsdtar "${@:2}"   
    ;;

    "-t"|"--tar")
        tar "${@:2}"
    ;;

    *)
        echo "Invalid option"
        exit 1
    ;;
esac
The wrapper script for the archiving utilities

Here, we see three code blocks in the case statement. The script executes the first block when the utility variable matches the string -b or --bsdtar. The script executes the second block when the variable matches -t or --tar. The third block handles an invalid input parameter.

Here is an example of how we can launch the script:

./tar-wrapper.sh --tar
...