-3

I have a file with a list of words in it. How would I read the file and then create a menu so I could choose an animal from the list? Simple bash script, nothing fancy.

Example: animal.txt

dog
cat
lion
bear

Example: Desired menu

1 - dog
2 - cat
3 - lion
4 - bear

Select choice: 3

You chose a lion.
  • 2
    What have you tried to do? How far did you get, what problems did you face? – ilkkachu Feb 5 at 20:35
0

We don't generally do requests for scripts here, but I'll help you with the difficult bit.

Assuming a shell with the select functionality (such as bash). This should get you started:

#!/bin/bash

PS3='Select choice: '
select ch in "dog" "cat" "lion" "bear"; do
    case $REPLY in
        [1-4]) break ;;
            *) echo 'Try again' >&2
    esac
done

printf 'You chose a %s\n' "$ch"

select in bash will display a menu and a prompt. The prompt is given by the value of the variable PS3.

The select statement is a loop, and in each iteration, the user will have made a choice. The choice number (or whatever the user types) is in $REPLY, and the actual menu item is in the variable given to the select statement (here it's $ch).

The case statement in the loop tests whether a valid response was given. If so (i.e. $REPLY was a single digit between 1 and 4), we break out of the loop. If any other thing was typed by the user, a short error message is printed and the loop runs its next iteration.

If you have more than 9 menu items, you may want to test for valid input in a more sophisticated way, since the $REPLY value may have more than one character in it.

After the loop, the choice from the menu is available in $ch.

  • Thank you for this. It is very helpful and produces the results I was looking for. – Scott Kampen Feb 5 at 22:06
1

Use mapfile and select.

e.g.

#!/bin/bash

mapfile -t animals < "animal.txt"

select animal in "${animals[@]}"; do
    echo "$animal"
    break
done

run:

$ ./animal.sh
1) dog
2) cat
3) lion
4) bear
#? 2
cat
  • Thanks for the help. That is exactly what I was looking for. – Scott Kampen Feb 5 at 22:06

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.