Bash - Switch Case

Tags:

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 $?
Written on November 13, 2022 at 20:48

Last but not least

If the post is updated, the creation date, will be pushed. So it might happend, you see an existing page back on frontpage. I think, this approach is valid, so wrong information or gained information is covered. But if I am going to write a new part of topic, I might include an updated link to the new post.

Home