Linux variable based on user selection

I am trying to write a script and make it as clean and lightweight as possible. In short, I want to present a menu and select a person that matches their favorite color. From there, I want to take the name of the color that was numbered in the menu and use it as a variable to be placed in a script elsewhere. My goal is to have one syntax after the menu, but will use a color variable. This is the only thing that turns me off. Below is a snippet .. any thoughts?

color_pref=
while [ -z "$color_pref" ] ;
do
echo
echo
echo "  ***************************************"
echo " What is your favorite color? "
echo "  1 - red"
echo "  2 - blue"
echo "  3 - green"
echo "  4 - orange"
echo "    Select 1, 2, 3, or 4 :" \n
echo "  ***************************************"
printf "    Enter Selection> "; read color_pref
echo [[[whatever variable is for color selected]]]

      

+3


source to share


3 answers


You can use a case statement to convert a value equal to a color based on a selected number.

case $color_pref in
    1) color=red ;;
    2) color=blue ;;
    3) color=green ;;
    4) color=blue ;;
    *) printf "Invalid color choice: %s" "$color_pref" >&2
       exit;
esac

      



You might want to look at a command select

that takes care of much of the menu display and selection for you.

+1


source


You can also use an associative array:

declare -A colors=( [1]=red [2]=blue [3]=green [4]=orange )

      

Example:

declare -A colors=( [1]=red [2]=blue [3]=green [4]=orange )
color_pref=
while [ -z "$color_pref" ]
do
echo
echo
echo "  ***************************************"
echo " What is your favorite color? "
echo "  1 - red"
echo "  2 - blue"
echo "  3 - green"
echo "  4 - orange"
echo "    Select 1, 2, 3, or 4 :" \n
echo "  ***************************************"
printf "    Enter Selection> "; read color_pref
echo ${colors[$color_pref]}
done

      



Or an indexed array:

declare -a colors=('invalid' 'red' 'blue' 'green' 'orange' )

      

Using:

echo ${colors[$color_pref]}

      

+1


source


You can store FLOWERS in an array like

COLORS=('red' 'blue' 'green' 'orange')

      

Then you can repeat the selected value with

echo $color_pref ${COLORS[color_pref-1]}

      

And you need to add

done

      

to end the cycle. All together something like

#!/usr/bin/env bash

COLORS=('red' 'blue' 'green' 'orange')
color_pref=
while [ -z "$color_pref" ] ;
do
        echo
        echo
        echo "  ***************************************"
        echo " What is your favorite color? "
        echo "  1 - red"
        echo "  2 - blue"
        echo "  3 - green"
        echo "  4 - orange"
        echo "    Select 1, 2, 3, or 4 :" \n
        echo "  ***************************************"
        printf "    Enter Selection> "; read color_pref
        echo $color_pref ${COLORS[color_pref-1]}
done

      

0


source







All Articles