Bash Select (Make Menus)

The select command in Bash is a powerful tool for constructing user-friendly menu-driven scripts. It presents a list of options to the user, numbered sequentially, and prompts them to enter the corresponding number to make a selection. The selected option triggers the execution of specific commands, allowing you to create interactive and flexible scripts.

Syntax:
select VARNAME ["in" WORD LIST] do ACTION_BLOCKS; done
  1. VARNAME:A variable to store the user's chosen option (usually a single word).
  2. WORD LIST:A list of options that users can see and choose from, separated by spaces. You can enclose the list in double quotes if it contains spaces or special characters.
  3. ACTION_BLOCKS:Commands to be executed based on the user's selection. Each option corresponds to one or more commands within a separate block.
Key Points:
  1. The numbered menu is displayed after select.
  2. The user's selection is read using read -r $REPLY.
  3. If the selection matches an option number, the corresponding ACTION_BLOCKS are executed.
  4. If not, the menu is displayed again.
  5. Use break inside an ACTION_BLOCKS to exit the select loop.
  6. Set PS3 to customize the prompt displayed before each selection.
Examples:

Basic Menu

PS3="Please select an option: " select option in "Option 1" "Option 2" "Exit"; do case $option in "Option 1") echo "You chose Option 1!" ;; "Option 2") echo "You chose Option 2!" ;; "Exit") break ;; esac done

Handling Invalid Input

PS3="Enter a number (1-3) or 'q' to quit: " select option in "1: List files" "2: Create file" "3: Delete file" "q: Quit"; do case $REPLY in 1) ls -l ;; 2) read -p "Enter filename: " filename touch "$filename" ;; 3) read -p "Enter filename: " filename rm "$filename" ;; q) break ;; *) echo "Invalid selection." ;; esac done

Using Substrings for Complex Input

PS3="Choose an operation (A=add, S=subtract, M=multiply, D=divide, Q=quit): " select operation in "A: Add" "S: Subtract" "M: Multiply" "D: Divide" "Q: Quit"; do read -p "Enter two numbers: " num1 num2 case $REPLY in A) result=$(($num1 + $num2)) ;; S) result=$(($num1 - $num2)) ;; M) result=$(($num1 * $num2)) ;; D) if [[ $num2 -eq 0 ]]; then echo "Error: Division by zero." else result=$(($num1 / $num2)) fi ;; Q) break ;; *) echo "Invalid operation." ;; esac if [[ ! -z "$result" ]]; then echo "Result: $num1 $REPLY $num2 = $result" fi done

Conclusion

The select command in Bash is used to create interactive menus in the terminal. It allows users to choose options from a list, with corresponding actions executed based on their selection using a simple case statement. The menu loop continues until the user decides to exit, providing a straightforward way to implement interactive scripts.