[bash] dynamically create case options

Assuming i got array from some dynamic command that can return whatever number of items.

What i would like to get is something like that:

array=('item 1' 'item 2' 'item 3')

local choice
while true;
do
    echo
    for i in "${!array[@]}";
    do
        echo "  [$i] ${array[$i]}"
    done
    echo
    read -p "-> " choice

    case $choice in
        0) echo "item 1" ;;
        1) echo "item 2" ;;
        2) echo "item 3" ;;
        *) echo "Wrong option" ;;
    esac
done

Like [i]) echo ${array[$i]}
I'm not sure how to correctly loop case states so they would work...

exists command select :wink:

1 Like

Yeah that's one way of doing it, but in select i have those problems:

  1. What if you want to customize looks of output for it's options?
  2. I don't get how to threat matching options inside select like if it's one of those from array -> do something?

    select option in ${array[@]}
    do
        case $option in
            array_option) echo "$option_index" && echo "$option" && doSomethingElse ;;
            *) echo "Wrong option" ;;
        esac
    done

Not sure how to catch array_option in that case and also get "$option_index", if that makes sense?

If you are dealing with a selection from an array of possibilities, instead of using a case, just iterate over it and break out of the loop when you find a match.

Alternatively, if your data is in an array and you can't predict it ahead of time, can't you just select the xth element of the array to get the value?

This is one of those situations where it is hard to answer without a more specific example.

If you truly want to generate a dynamic case statement. You could write code that generates a shell script and then call that shell script. That probably isn't the best way to solve the problem though.

Can you give an example of how it would look inside select? Not sure i follow...

Perhaps something like that with awk is what i meant in the first place

is this your problem ? different action from array content and not from $choice ?

while true;
do
    echo
    for i in "${!array[@]}";
    do
        echo "  [$(($i+1))] ${array[$i]}"
    done
    ((i++))
    echo
    read -p "-> " choice
    [ -z "$choice" ] && choice=-1
    if (( "$choice" > 0 && "$choice" <= $i )); then
        item="${array[$(($choice-1))]}"
        echo "$item"
        if [[ "$item" =~ "uefi" ]]; then # or case ...
            echo "disk uefi"
            # loaddisk 0 "$item"
        #else ...
             # loaddisk 1 "/${item}/"
        fi
        break
    else
        echo "Wrong option"
    fi
done
3 Likes

Exactly!

Brilliant, wish there would be something little more elegant, but it does job just fine :slight_smile:

P.S. Thx again for reading my mind...I'm having trouble lately formulating my thoughts

Forum kindly sponsored by