yaserso
yaserso

Reputation: 2868

Dynamic option selection in bash?

I've got a variable in the script that has several lines of single words

Say $loremipsums is basically this:

something1
something2
something3
something4

Now $loremipsums is dynamic; it can be more or less, and can be different values depending on what it reads from a certain file. I also want to use what the user chose in a variable.

I want to make them into an option selection menu dynamically. I found one that shows the basic one here: https://askubuntu.com/questions/1705/how-can-i-create-a-select-menu-in-a-shell-script

Now I need to do it dynamically. As you can see, they're set manually through that example.

Here is an example of what I want:

1) michael
2) richard
3) steven
4) robert
5) exit
Please enter your choice: 4
You have chosen robert

Upvotes: 3

Views: 6145

Answers (2)

Gilles Quénot
Gilles Quénot

Reputation: 185161

Do you know select ?

names=( michael richard steven robert exit )
select name in "${names[@]}"; do
    echo "You have chosen $name"
    [[ $name == exit ]] && break
done

Upvotes: 13

glenn jackman
glenn jackman

Reputation: 246817

To split $loremipsums on newlines, and select one of them:

oldIFS=$IFS
IFS=$'\n'
choices=( $loremipsums )
IFS=$oldIFS
PS3="Please enter your choice: "
select answer in "${choices[@]}"; do
  for item in "${choices[@]}"; do
    if [[ $item == $answer ]]; then
      break 2
    fi
  done
done
echo "$answer"

Upvotes: 7

Related Questions