Skip to content

Bash - Switch Case

Posted on:November 13, 2021 at 09:47 PM

Switch case in bash script

I like to use this case switch in a bash. Allows for common mistypes and multiple inputs. This can be easily extended with getops.

#!/bin/bash
script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
flow=$1
# Decide which flow to run.
case $flow in
    "b"|"build")
        # build sth
        ;;
    "c"|"clippy")
        clippy
        ;;
    "d"|"dev")
        # your run a development suite
        ;;
    "d:b")
        docker build -t sth/sth .
        ;;
    "f"|"fmt")
        fmt
        ;;
    "r"|"run")
        cargo run
        # or sth else
        ;;
    "t"|"test")
        cargo test
        # or npm run test
        ;;

    "w"|"watch")
        cargo watch -x run
        # or whatever
        ;;
    *)
        echo "Nothing selected"
        ;;
esac
exit $?

Example: Wekan CLI

See the full code here: Wekan CLI manager or in the E2E script Wekan CLI E2E manager

case $flow in
    "b"|"build")
        echo "Build without feature"
        cargo build
        echo "Build feture store"
        cargo build --features store
        echo "Build integration"
        cargo build --features integration
        ;;
    "b:target")
        echo "Build release binary"
        release $selection
        ;;
    "c"|"clippy")
        clippy $selection
        ;;
    "cov"|"lcov")
        mozilla_gcov $selection
        ;;
    "d"|"dev")
        cd $script_dir
        export EMACSSAVEMODEDIR=.
        emacs
        ;;
    "d:b")
        docker build -t concafe/wekan-cli:release .
        ;;
    "e"|"e2e"|"2e"|"2ee")
        e2e $selection
        ;;
    "f"|"fmt")
        fmt
        ;;
    "r"|"run")
        run $selection
        ;;
    "r:s")
        run cli-store
        ;;
    "t"|"test")
        test_crates $selection
        ;;
    "ts")
        echo "TEST cli with feature store"
        test_crates cli-store
        ;;
    "qa"|"q")
        echo "QA (fmt, clippy, ut, e2e)"
        set -e
        fmt
        clippy
        echo "TEST"
        test_crates
        e2e
        ;;
    *)
        echo "Nothing selected"
        ;;
esac
exit $?