One background
In the recent operation and maintenance work, many scripts have been written, and some efficient uses have been found when writing these scripts. Now, let's briefly introduce the use of select.
2. Examples
select expression is an extended application of bash, which is good at interactive occasions. Users can choose from a different set of values. The format is as follows:
select var in ... ; do ... done
2.1 select alone
#!/bin/bash Hostname=( 'host1' 'host2' 'host3' ) select host in ${Hostname[@]}; do if [[ "${Hostname[@]/${host}/}" != "${Hostname[@]}" ]] ; then echo "You select host: ${host}"; else echo "The host is not exist! "; break; fi done
Operation result display:
[root@gysl ~]# sh select.sh 1) host1 2) host2 3) host3 #? 1 You select host: host1 #? 2 You select host: host2 #? 3 You select host: host3 #? 2 You select host: host2 #? 3 You select host: host3 #? 1 You select host: host1 #? 6 The host is not exist!
A judgment is added in the script. If the selected host is not in the specified range, the execution will be ended.
2.2 use in combination with case
#!/bin/bash Hostname=( 'host1' 'host2' 'host3' ) PS3="Pease input the number of host: " select host in ${Hostname[@]}; do case ${host} in 'host1') echo "This host is: ${host}. " ;; 'host2') echo "This host is: ${host}. " ;; 'host3') echo "This host is: ${host}. " ;; *) echo "The host is not exist! " break; esac done
Operation result display:
[root@gysl ~]# sh select.sh 1) host1 2) host2 3) host3 Please input the number of host: 1 This host is: host1. Please input the number of host: 3 This host is: host3. Please input the number of host: 4 The host is not exist!
In many scenarios, it is more convenient to use case statements. In the above script, the value of PS3 is redefined. By default, the value of PS3 is' ×? '.
Three summary
3.1 select seems unimportant, but it is very useful in interactive scenes. I hope you can summarize a lot of usage.
3.2 the article also involves the use of bash shell to determine whether the value is in the array.