Skip to content
Usman Zubair
Go back

Bash: Using case statements

Recently I found myself writing a simple docker-compose wrapper script in Bash. Here is how to read command line arguments in a Bash script. Nested IF statements might be nice but for more complex conditionals, using the case syntax is the way to go.

Here is a quick example:

#!/bin/bash

# Make sure we have atleast one option provided
if [[ ${#} -eq 0 ]]; then
    # implement show_usage function
    show_usage
fi

option="$1"
case ${option} in
    --help)
        # implement show_usage function
        show_usage
        ;;
    --up)
        # implement start_containers function
        start_containers
        ;;
    --down)
        # implement stop_containers function
        stop_containers
        ;;
    --start=*)
        # implement start_service function
        opt_value=${option#*=}
        start_service ${opt_value}
        ;;
    *)
        # implement show_usage function
        show_usage
        ;;
esac


Previous Post
Debugging Tomcat on a Server
Next Post
AWS Lambda for thumbnail generation