Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux variable based on user selection

I am trying to write a script and make it as clean and light as possible. In short I want to present a menu and have a person pick a number that corresponds with their favorite color. From there I want to take the color name that was with the number in the menu and use it as a variable that will be placed in the script elsewhere. My goal is to have one syntax after the menu but will use the color variable. This is the one piece that is setting me back. 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]]]
like image 573
Cool_beans Avatar asked Mar 11 '26 20:03

Cool_beans


2 Answers

You can use a case statement to convert set a variable equal to a color based on the number chosen.

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 may want to look at the select command, which takes care of much of the menu display and choice selection for you.

like image 90
chepner Avatar answered Mar 13 '26 08:03

chepner


You can use an associative array too:

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 indexed array:

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

Usage:

echo ${colors[$color_pref]}
like image 21
Jahid Avatar answered Mar 13 '26 10:03

Jahid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!