select menu items in ksh

Posted by david marsh on Fri 11 April 2008

Update: This has a few bugs and end condition errors. See Take 2 for a better version.

A little ksh shell script I wrote to turn menu items on and off. It's not pretty.

#!/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

    if expr $choice + 0 1>/dev/null 2>&1 ; then
        if [ -z "${item[$choice]}" -a $choice -le $itemnum ] ; then
            if [ "${selected[$choice]}" = "${inv}x" ] ; then
                selected[$choice]="${nml} "
                final[$choice]=""
            else
                selected[$choice]="${inv}x"
                final[$choice]="${items[$choice]}"
            fi
        else
            msg="$choice is not valid"
        fi
    else
        break
    fi
done

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

tags: shell, unix