select Loops for Simple Menus

Su Suriya Ravichandran Updated 06 Dec 2026
10 min read ·Lesson 86 of 205

The select loop is a Bash feature that builds a numbered menu from a list of words, asks the user to pick a number, and runs the loop body with the chosen word. It repeats until the script leaves the loop with break (or return or exit) or until the input ends. With only a few lines you get a working text menu, without printing the options, numbering them or checking that the number is valid by yourself.

select is part of Bash (and Ksh), not of the POSIX shell standard, so scripts that use it need a #!/usr/bin/env bash shebang (lesson 26).

Syntax

select variable in word1 word2 word3; do
    commands
done

The structure looks like a for loop (lesson 78), but the behavior is different. A for loop walks through the list by itself. A select loop shows the list as a menu and waits for the user to choose one entry at a time.

Basic Example

select fruit in apple banana cherry; do
    echo "you chose: $fruit (REPLY=$REPLY)"
done

A session, where the numbers 2 and 1 are typed by the user and the last prompt ends with Ctrl + D:

1) apple
2) banana
3) cherry
#? 2
you chose: banana (REPLY=2)
#? 1
you chose: apple (REPLY=1)
#? 

Each pass of the loop does the following:

  1. On the first pass (and again in the cases listed below) Bash prints the menu, one numbered entry per item.
  2. Bash prints the prompt #? and reads one line from standard input.
  3. If the line is a number between 1 and the number of items, the loop variable (fruit) is set to the matching word.
  4. The variable REPLY always holds the exact text the user typed.
  5. The commands between do and done run once.
  6. Bash goes back to step 2. The menu is not printed again unless the user types an empty line.

The loop ends only when something inside it leaves the loop, or when the input reaches its end (Ctrl + D at the prompt). The example above has no break, so you must press Ctrl + D to leave it.

Leaving the Loop

A menu almost always includes an entry that ends it. The usual pattern is a case statement (lesson 75) inside the loop, with a break in the branch for the quit option:

PS3="Pick one: "
select item in start stop quit; do
    case $item in
        start) echo "starting" ;;
        stop)  echo "stopping" ;;
        quit)  echo "bye"; break ;;
        *)     echo "invalid: REPLY=[$REPLY]" ;;
    esac
done
echo "after the loop"

A session in which the user types 1, 7, abc, an empty line, 2 and 3:

1) start
2) stop
3) quit
Pick one: 1
starting
Pick one: 7
invalid: REPLY=[7]
Pick one: abc
invalid: REPLY=[abc]
Pick one: 
1) start
2) stop
3) quit
Pick one: 2
stopping
Pick one: 3
bye
after the loop

The same break command from lesson 84 ends the loop, and the script continues after done. The loop returns status 0 after a break.

Choosing the end of the loop in the case branch has an advantage: the quit entry is part of the menu, so the user can see how to leave.

If the user presses Ctrl + D instead, the loop ends as well. In the test runs this printed an empty line and the loop finished with status 1. A script that needs to tell a normal quit from end of input can check $? right after done.

Changing the Prompt with PS3

The prompt text is stored in the variable PS3. Bash uses #? when PS3 is not set. The first Bash prompt variable most people meet is PS1, the main shell prompt (lesson 145); PS3 is the one used only by select.

PS3="Choose an action (number): "

Set it before the loop. You can also set it only for one function with local PS3=... (lesson 92), so the change does not leak into the rest of the script.

REPLY and Invalid Choices

The loop variable and REPLY have different jobs:

VariableContents
The loop variable (fruit, item)The menu word that matches the number, or an empty string if the reply was not a valid number
REPLYThe exact line the user typed, including spaces

An invalid reply does not stop the loop and does not print an error. Bash simply runs the body with an empty loop variable:

select y in a b; do
    echo "y=[$y] REPLY=[$REPLY]"
    [ -n "$y" ] && break
done

With the replies 9, zz and 1:

1) a
2) b
#? 9
y=[] REPLY=[9]
#? zz
y=[] REPLY=[zz]
#? 1
y=[a] REPLY=[1]

This is why the *) branch of the case statement above is important. It receives every invalid reply, and it can use $REPLY to say what was typed. A reply with several numbers, like 1 2, is also invalid and leaves the loop variable empty. A number with spaces around it, like 02, was accepted as 2 in the test run, and REPLY kept the spaces.

An empty line is special: it prints the menu again, and the body does not run. This lets users see the options again when the menu has scrolled off the screen.

Where the Menu and Prompt Are Printed

The menu and the prompt are written to standard error, not standard output (lesson 56). Only the output of your own commands in the loop body goes to standard output. This means that

select choice in one two; do break; done > result.txt

still shows the menu on the screen and keeps the file free of menu text. It also means that 2>/dev/null hides the menu completely, which is rarely what you want in an interactive script.

The input is read from standard input. If your script itself reads data from a pipe or a file, the menu will read from the same place. Use the file-descriptor technique from lesson 83 (read -u 3) for data, or read the data into an array before the menu starts.

The List of Choices

The word list after in is an ordinary shell word list. It can come from a glob pattern, an array or the script's arguments.

A glob pattern

select f in *.txt; do
    echo "file=[$f]"
    break
done

In a folder holding a.txt, b c.txt and notes.md, the menu shows

1) a.txt
2) b c.txt
#? 2
file=[b c.txt]

Quote "$f" whenever you use the variable, because the name b c.txt contains a space (lesson 55).

An array

options=("Show date" "Show disk usage" "List this folder" "Quit")
select choice in "${options[@]}"; do
    ...
done

The quoted "${options[@]}" form keeps each element as one menu entry, even when an element contains spaces. Arrays are explained in lessons 97 to 101.

The script or function arguments

When you leave out in word ..., select uses the positional parameters, just like for does:

set -- one two three
select p; do echo "p=$p"; break; done
1) one
2) two
3) three
#? 3
p=three

Inside a function, the list is the function's own arguments. That makes it easy to write a reusable chooser:

choose() {
    select o in "$@"; do
        echo "o=$o"
        break
    done
}
choose "red apple" "green pear"
1) red apple
2) green pear
#? 2
o=green pear

An empty list

If the list expands to nothing, for example select a in $nothing with an unset variable, the loop does not run, nothing is printed, and the status is 0.

How the Menu Is Laid Out

For a short list Bash prints one entry per line. For a longer list it arranges the entries in columns to fit the terminal width. The width comes from the variable COLUMNS. A list of ten words with COLUMNS=40 looked like this:

1) alpha      5) epsilon   9) iota
2) beta       6) zeta     10) kappa
3) gamma      7) eta
4) delta      8) theta

You usually do not need to set COLUMNS yourself. In an interactive terminal Bash keeps it up to date. Entries are numbered from 1, and the numbers are right-aligned when the list has more than nine items.

A Complete Menu Script

This script combines everything above. It uses an array for the entries, a custom prompt, a case statement, a branch for invalid input and a way out:

#!/usr/bin/env bash
PS3="Choose an action (number): "
options=("Show date" "Show disk usage" "List this folder" "Quit")

select choice in "${options[@]}"; do
    case $choice in
        "Show date")
            date +%F
            ;;
        "Show disk usage")
            df -h . | tail -n 1
            ;;
        "List this folder")
            ls
            ;;
        "Quit")
            echo "Goodbye."
            break
            ;;
        *)
            echo "Invalid choice: '$REPLY'. Enter 1-${#options[@]}."
            ;;
    esac
done

In a folder that holds a.txt and b.txt, a session where the user types 3, 9, x, 1 and 4 prints

1) Show date         3) List this folder
2) Show disk usage   4) Quit
Choose an action (number): 3
a.txt
b.txt
Choose an action (number): 9
Invalid choice: '9'. Enter 1-4.
Choose an action (number): x
Invalid choice: 'x'. Enter 1-4.
Choose an action (number): 1
2026-11-21
Choose an action (number): 4
Goodbye.

The date and the df result depend on the machine and the day. The expression ${#options[@]} is the number of array elements (lesson 101), so the error message stays correct if you add more entries. The case patterns match the menu words, not the numbers, which keeps the code readable even if you reorder the entries.

Picking a File and Handling Cancel

A menu often needs a "Cancel" entry that is not part of the data. Add it to the end of the list and test for it before the generic checks:

#!/usr/bin/env bash
cd "$1" || exit 1
shopt -s nullglob
files=(*.txt)
if (( ${#files[@]} == 0 )); then
    echo "No .txt files here." >&2
    exit 1
fi

PS3="File number: "
select file in "${files[@]}" "Cancel"; do
    if [[ $file == "Cancel" ]]; then
        echo "Cancelled."
        break
    elif [[ -n $file ]]; then
        echo "Selected: $file ($(wc -c < "$file") bytes)"
        break
    else
        echo "Please enter a number from the list."
    fi
done

Run on a folder with a.txt (6 bytes) and b.txt (empty), after the user types 0 and then 1:

1) a.txt
2) b.txt
3) Cancel
File number: 0
Please enter a number from the list.
File number: 1
Selected: a.txt (6 bytes)

The nullglob option (lesson 149) makes *.txt expand to nothing when no file matches, so the array is empty and the script can report that instead of showing a menu with the literal text *.txt. The test -n $file is true for valid choices and false for invalid ones.

Using continue and return

continue inside select skips the rest of the body and shows the prompt again, exactly as in the loops from lesson 84. In a function, return leaves the loop and the function together:

menu() {
    local PS3="num> "
    select c in add list exit; do
        case $c in
            add)  echo adding ;;
            list) echo listing ;;
            exit) return 0 ;;
            *)    echo "bad [$REPLY]" ;;
        esac
    done
    echo "menu ended by end of input"
}

If the user types 1, 2, 8 and 3:

1) add
2) list
3) exit
num> 1
adding
num> 2
listing
num> 8
bad [8]
num> 3

and the function returns right away, so the final echo is not printed. If the user presses Ctrl + D instead of choosing exit, the loop ends, the last echo runs and the function returns 0. Using local PS3 inside the function restores the old prompt when the function returns. Functions are covered in lessons 88 to 92.

Portability

select is not available in Dash or in other strictly POSIX shells. Running a script with select under Dash fails when the shell reads the line:

d86.sh: 1: Syntax error: "do" unexpected

For a script that must run under sh, build the menu by hand with echo, read and a case statement inside a while loop (lessons 31 and 80). Lesson 134 shows a hand-made interactive menu, and lessons 188 and 189 explain how to separate Bash-only syntax from POSIX syntax.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about select Loops for Simple Menus and get answers drawn from it.

Signed-in readers only.