How to use select loops in BASH

Home > Search > How-to
  by

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.

#!/bin/bash
Fruit=(banana orange apple grape)

echo "Select your favorite fruit"

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

 

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

~]# ./example.sh

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.

#!/bin/bash
Files=($(ls /path/to/directory))

echo "Select a file"

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

 

Running the script.

~]# ./example.sh

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.

#!/bin/bash
Presidents=($(cat /tmp/presidents))

echo "Select a president"

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

 

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

~]# ./example.sh

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.




Comments