How to use select loops in BASH

Home > Search > How-to

A select loop can be used to produce a list of selectable items for a user to select. For example, let's say you want to prompt a user to select a certain fruit, such as banana, orange, apple, or grape.

Fruit=(banana orange apple grape)

echo "Select your favorite fruit"

select myFruit in "${Fruit[@]}"
    echo "You selected" $myFruit


When running this script, the user will be prompted to select banana or orange or apple or grape.

~]# ./

Select your favorite fruit

1) banana
2) orange
3) apple
4) grape


Select files in a directory

The Files variable lists the files in a directory. Two sets of parenthesis are used so that parenthesis are placed around the files in the directory, such as (File1 File2 File3). The parenthesis are needed so that the select loop recognizes that the data inside of the parenthesis is an array of data.

Files=($(ls /path/to/directory))

echo "Select a file"

select myFile in "${Files[@]}"
    echo "You selected" $myFile


Running the script.

~]# ./

Select a file

1) File1
2) File2
3) File3


Select data in a file

Let's say the /tmp/presidents file contains the presidents of the USA, such as Obama Clinton Bush. The following script will prompt you to select a president.

Presidents=($(cat /tmp/presidents))

echo "Select a president"

select myPresident in "${Presidents[@]}"
    echo "You selected" $myPresident


When running the script, you will be prompted to select a president.

~]# ./

Select a president

1) Obama
2) Bush
3) Clinton


Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter in the box below so that we can be sure you are a human.