Bash select statement

In Bash, the select statement is used to create a simple menu-driven interface in the terminal. It allows the user to select options from a list and performs an action based on their choice. Here’s the basic syntax of a select statement in Bash:

select variable in option1 option2 option3 ...; do
    # Code to execute
done

The select statement displays a numbered menu of options to the user. The user can enter the corresponding number to select an option. The selected option is then stored in the variable. The code block inside the select loop is executed for each selected option.

Here’s an example that demonstrates the usage of a select statement in Bash:

#!/bin/bash

options=("Option 1" "Option 2" "Option 3" "Quit")

select choice in "${options[@]}"; do
    case $choice in
        "Option 1")
            echo "You selected Option 1"
            ;;
        "Option 2")
            echo "You selected Option 2"
            ;;
        "Option 3")
            echo "You selected Option 3"
            ;;
        "Quit")
            echo "Exiting..."
            break
            ;;
        *)
            echo "Invalid option"
            ;;
    esac
done

In this example, the select statement presents a menu to the user with four options: “Option 1”, “Option 2”, “Option 3”, and “Quit”. The user can enter the number corresponding to their desired option. The selected option is stored in the choice variable. The code block inside the select loop then uses a case statement to perform different actions based on the selected option.

When you run this script, it will display the menu:

1) Option 1
2) Option 2
3) Option 3
4) Quit

The user can enter the number corresponding to their choice. If an invalid option is entered, the *) branch of the case statement is executed.

Here’s an example of the output when the user selects “Option 2”:

You selected Option 2

If the user selects “Quit”, the loop is exited with the break statement.

The select statement provides a convenient way to create interactive menus in Bash scripts, allowing users to make selections and perform actions based on their choices.

Leave a Comment

Your email address will not be published. Required fields are marked *