Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print out a list of all cases of a switch

Tags:

bash

Curious question. Is it somehow possible to print out all cases of a certain switch-case automatically in bash? In a way, such that it stays as maintainable as possible, meaning that one does not have to add any more code if a new case is added to print out that same case.

For instance, that would be useful if the cases represented commands. A help function could then print out all available commands.

like image 445
Alex Avatar asked Feb 23 '17 16:02

Alex


2 Answers

There is no direct way to achieve this, but you can use an array to maintain your choices:

# Define your choices - be sure not to change their order later; only
# *append* new ones.
choices=( foo bar baz )

# Make the array elements the case branches *in order*.
case "$1" in
    "${choices[0]}")
        echo 'do foo'
        ;;

    "${choices[1]}")
        echo 'do bar'
        ;;

    "${choices[2]}")
        echo 'do baz'
        ;;

    *)
        echo "All choices: ${choices[@]}"

esac

This makes the branches less readable, but it's a manageable solution, if you maintain your array carefully.

Note how the branch conditions are enclosed in "..." so as to prevent the shell from interpreting the values as (glob-like) patterns.

That said, as chepner points out, perhaps you want to define your choices as patterns to match variations of a string:

In that event:

  • Define the pattern with quotes in the choices array; e.g., choices=( foo bar baz 'h*' )

  • Reference it unquoted in the case branch; e.g., ${choices[3]})

like image 115
mklement0 Avatar answered Sep 28 '22 05:09

mklement0


bash does not give you access to the tokens it parses and does not save case strings (which can be glob expressions as well).

Unfortunately, that means you will not be able to DRY your code in the way you were hoping.

like image 28
Greg Tarsa Avatar answered Sep 28 '22 06:09

Greg Tarsa