Interactive Menu in Shell

Level 5228 keystrokes

select prints a numbered menu, shows the PS3 prompt and runs its body for each choice until break. The output shows a session where the user enters 2 (the date, which varies) and then 4 to quit.

Shell code

# PS3 is the prompt select shows when asking for a choice
1PS3="Select option: "
# Menu entries; quotes keep each multi-word entry together
2options=("List files" "Show date" "Disk usage" "Quit")
# Print the numbered menu, then read a choice on every iteration
3select opt in "${options[@]}"; do
# $REPLY is the number typed; opt is the matching entry text
4 case $REPLY in
5 1) ls -la ;;
6 2) date ;;
7 3) df -h ;;
# break leaves the select loop
8 4) echo "Goodbye!"; break ;;
# Any other input: show an error and ask again
9 *) echo "Invalid option" ;;
10 esac
11done

Output

1) List files
2) Show date
3) Disk usage
4) Quit
Select option: 2
Mon Jan 15 10:30:45 UTC 2024
Select option: 4
Goodbye!
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • "× 16
  • ;× 12
  • )× 6
  • -× 2
  • =× 2
  • $× 2
  • :× 1
  • !× 1
  • (× 1
  • [× 1

More Shell examples at level 5

← Shell typing practice