Miscellaneous bash features

select - select is like a cross between a while loop and a for loop that displays its list as a menu and then repeats a read until one of the action-cmds issues a break.

Structure :

select var in list
do
  action-cmds
done

When executed, select displays each string in list as a menu element and numbers each element sequentially. It will then provide the PS3 prompt and wait for input. If a string is quoted, its contents will be treated as a single menu element.

The user selects the desired menu choice by entering the number displayed to the left of the list element. The element selected is copied to the variable specified immediately after the select keyword.

Keep in mind the whole menu item is copied, so if your menu item was "My favorite year", all three words will be copied to the variable. So, keep your menu items short and sweet.

select is an endless loop, so the break command must be used to exit the select loop.

Example :

query() {
  select ans in nope "try again" quit "give up"
  do
    if [ "$ans" = quit ]
    then
      break
    fi

    if [ "$ans" = "give up" ]
    then
      break
    fi

    echo "You picked $ans"

  done
}

  • Once user enters a choice and presses [enter], the selection is processed in the action body.

  • If there is no break out of the loop, the select prompt will be displayed again, even if the choice entered is invalid.

  • An invalid or [enter] with no choice will assign a null value in the choice variable. The loop body will be run. And the select prompt will be re-displayed.

  • The variable set by select keeps the assigned string after the execution breaks out of the select loop. So, you may use select to get valid input from the user and process the choice outside the loop.


  • graves, ` ` may be used to generate elements in the select list.