[Shell] select usage

       select can be used for looping. Similar to other loops, select depends on the conditional judgment at the top or bottom of the code block to determine the branch of the program. In terms of multi-menu display and user input, select can easily output menus for users to choose and use. The select statement is generally used with the case statement, and its syntax format is:

select choice in menu_1,menu_2,menu_3...
do
    case "$choice" in
        menu_1)
            cmd
            ;;
        menu_2)
            cmd
            ;;
        ...
        menu_m)
            break
            ;;
        menu_n)
            exit
            ;;
    esac
done

Use example: display computer system related information

#! /bin/bash
select choice in disk_partition file_sys cpu_load mem_util quit
do 
	case "$choice" in
		disk_partition)
			fdisk -l
			;;
		file_sys)
			df -h
			;;
		cpu_load)
			uptime
			;;
		mem_util)
			free -m
			;;
		q)
			break
			;;
		*)
			echo "error"
			exit
			;;
	esac
done

Results of the:

       It can be seen from the above running results that the menu options appear after executing the shell script, and they only appear once. So if there are many options that need to be viewed at one time, it may not be so convenient. Combined with the while loop, the menu options can be displayed every time the input is entered. The encoding is as follows:

#! /bin/bash
# PS3 = "Your choice is[5 for exit]:"
while true;do
	select choice in disk_partition file_sys cpu_load mem_util quit
	do 
		case "$choice" in
			disk_partition)
				fdisk -l
				break
				;;
			file_sys)
				df -h
				break
				;;
			cpu_load)
				uptime
				break
				;;
			mem_util)
				free -m
				break
				;;
			quit)
				break
				;;
			*)
				echo "error"
				exit
				;;
		esac
	done
	echo "-----------------------------------------------------------------------"
done

       By adding a while loop outside the select, the select statement is executed once for each match in the case statement, and the select statement is thus looped. The execution result is as shown in the figure below. After each input, the menu will be printed once

Guess you like

Origin blog.csdn.net/VinWqx/article/details/104966877