select menu items in ksh take 2

2008-04-16

So, my original select menu items in ksh script has a few bugs. Here’s a new version that should work a lot better. Now if you choose -1 or a number bigger than 1023 it won’t crash.

#!/usr/bin/ksh
nml="^[[0m"
inv="^[[7m"

while true ; do
    clear
    echo $msg
    itemnum=0
    for item in dog cat frog cow ; do
        (( itemnum = itemnum + 1 ))
        echo "${selected[$itemnum]:= } \
            $itemnum ${items[$itemnum]:=$item} ${nml}"
    done

    echo "choice: \c"
    read choice
     
    #check if it's a number #check it's between 1 and itemnum and it's valid
    if expr $choice + 0 1>/dev/null 2>&1 && \
        [ $choice -eg 1 -a $choice -le $itemnum -a -z "${item[$choice]}" ] ; then
        if [ "${selected[$choice]}" = "${inv}x" ] ; then
            selected[$choice]="${nml} "
            final[$choice]=""
        else
            selected[$choice]="${inv}x"
            case ${items[$choice]} in
            dog)
                final[$choice]="${items[$choice]} is a doggy!";;
            cat)
                final[$choice]="${items[$choice]} is a catty!";;
            frog)
                final[$choice]="${items[$choice]} is a froogy!";;
            cow)
                final[$choice]="${items[$choice]} is a moocow!";;
            *)
                echo "its f***ed!"
                exit 1;;
            esac
        fi
    elif [ "$choice" = "e" ] ; then
        break
    else
        msg="$choice is not valid"
    fi
done

echo "You picked: ${final[*]}" | tr -s " "

That’s about it.