Java Programming Tutorials

Java programming tutorials with many code examples!

Bash case statement

Problem:

How to use Bash case statement to process complex conditionals? It’s most often used to process script parameters.

Solution:

Instead of using bunch of Bash if-else statements to process parameters, its much better to use case-esac. In the following example we parse command line arguments passed to the script:

#!/bin/bash

function usage() {
    echo "$0 demonstrates Bash case command usage"
    exit 1
}

while [ ! -z "${1}" ]; do
    case "$1" in
        -o|--option)
            OPTIONS="$2"; shift 2;;
        -d|--directory)
            DIRECTORY="$2"; shift 2;;
        -h|--help)
            usage;;
        *)
            echo "Unknown param: '${1}'"
            usage;;
    esac
done

echo "Options: ${OPTIONS}"
echo "Directory: ${DIRECTORY}"

Note that in order to process a couple of different parameters in the same way, we use | (pipe) to separate the alternatives.

Here’s example of running the script:

$> ./case.sh --help
./case.sh demonstrates Bash case command usage
$> ./case.sh -x aoeu
Unknown param: '-x'
./case.sh demonstrates Bash case command usage
$> ./case.sh -o ab
Options: ab
Directory:
$> ./case.sh -o ab --option 23 --option 12
Options: 12
Directory:
$> ./case.sh -o 23 --directory /tmp
Options: 23
Directory: /tmp
Share with the World!