SoFunction
Updated on 2025-03-09

Simple example of using select command in Bash Shell

Preface
Today I just wrote an automated packaging script and used the bash shell again. I feel so happy. Here I mainly want to introduce the select command, which can help us complete the menu selection function.

Format
It is also the first time I have used select process control today, and the select function is not implemented in php, Java, and C languages. In Bash Shell, the select format is as follows:

  select $var in ${list[@]} 
  do 
    statements that can use $var 
  done 

When select is executed, a selection menu will be given based on the list array. The result after the user selects it is saved in the $var variable, and then the statements statement is executed. After the execution is completed, the menu is given again and wait for the user to select. If the user wants to break out of the selection loop, he needs to add a break statement according to the conditions in the loop body.

Example
Given an example of select, you can refer to:

 

  #!/bin/bash 
   
  fruits=( 
    "apple" 
    "pear" 
    "orange" 
    "watermelon" 
  ) 
   
  echo "Please guess which fruit I like :" 
  select var in ${fruits[@]} 
  do 
    if [ $var = "apple" ]; then 
      echo "Congratulations, you are my good firend!" 
      break 
    else 
      echo "Try again!" 
    fi 
  done