This article is also the fifth chapter of "Learning the bash Shell" 3rd Edition, Flow Control, 4 of Reading Notes, but we will not limit it to this. Flow control is a very common part of any programming language, including case. Here, we will continue to learn about them.
The select statement is different from other flow control statements. There are no similar statements in the C language (the select statement in C is used for socket, which has different meanings, rather than flow control ). The format is as follows:
Select
Name
[In
List
]
Do
Statements that can use $ name...
Done
Similar to the for format, you can delete the in list, that is, use the default in $ @. Using select, we can easily create a menu:
During execution, a menu is provided based on the list. After the user selects the menu, the statement is executed. The selected menu is placed in $ name. After execution, the menu is provided again, keep repeating. If you jump out of the loop, you can use break. Below is a basic example:
# Select Test Sample
# Test 1: Basic Usage Test
Function test
{
Echo 'select test 1'
Mystack = 'a 123 red'
Select entry in $ mystack; do
# If it is a valid choice, $ entry contains the value in the list. If it is an invalid choice, it is null. Therefore, it is often determined whether the selection is valid, for example, if [$ entry] is used.
If [$ entry]; then
Echo "You select the choice '$ entry '"
Break
** Note: Since select is a loop, break is used to exit the loop.
Else
Echo "Invaild selection"
Fi
Done
}
Test
Execution result
$./Select-test
Select test 1 ** note: the elements in the list are displayed as menus *
1)
2) 123
3) red
#?
H ** note: the prompt symbol #?, Wait for the user to enter and select. If you press enter, the menu is displayed again.
Invaild selection
#?
3
You select the chioce 'red'
Linux Bash Shell (5): Special files, aliases, options, and parameters
For the prompt, PS1 and PS2 are mentioned. In select, the prompt is given, that is, #? That is, the PS3. We can redefine the PS3 in shell. For example, PS3 = "Please select a choice :"
After statement is executed, the prompt will continue to appear. Wait for the next input. If you need to exit from the select loop, use break. If you type [Press enter], the menu is displayed again.
Related Links: My articles on Linux operations