Select is also a kind of loop, it is more suitable for use in the case of user choice. For example, we have one such requirement, after running the script, let the user go to select the number, select 1, run the W command, select the 2 run Top command, select 3 run the free command, select 4 to exit. The script implements this:
#!/bin/bash
echo "chose a number, 1:run W, 2:run top, 3:run free, 4:quit"
Echo
Select command in w top free quit
Do
Case $command in
W
W
;;
Top
Top
;;
Free
Free
;;
Quit
Exit
;;
*)
echo "Please input a number: (1-4)."
;;
Esac
Done
The results of the implementation are as follows: SH select.sh Chose a number, 1:run W, 2:run top, 3:run free, 4:quit
1) W 2) Top 3) Free 4) Quit #? 1 16:03:40 up, 2:42, 1 user, load average:0.01, 0.08, 0.08 USER TTY from [email protected] IDLE jcpu PCPU Root pts/0 61.135.172.68 15:33 0.00s 0.02s 0.00s sh select.sh
#? 3 Total used free shared buffers Cached mem:1020328 943736 76592 0 86840 263624 -/+ buffers/cache:593272 427056 swap:2097144 44196 2052948 #?
We found that select defaults to the command line for the sequence number, each time a number is entered, the corresponding command executes, and the command does not exit the script. It will continue to let us lose again as the serial number. The prompt before the sequence number, we can also modify, using the variable PS3 can, again modify the script as follows:
#!/bin/bash
ps3= "Please select a number:"
echo "chose a number, 1:run W, 2:run top, 3:run free, 4:quit"
Echo
Select command in w top free quit
Do
Case $command in
W
W
;;
Top
Top
;;
Free
Free
;;
Quit
Exit
;;
*)
echo "Please input a number: (1-4)."
Esac
Done
If you want the script to exit automatically each time you enter a sequence number, you will need to change the script again as follows:
#!/bin/bash
ps3= "Please select a number:"
echo "chose a number, 1:run W, 2:run top, 3:run free, 4:quit"
Echo
Select command in w top free quit
Do
Case $command in
W
W;exit
;;
Top
Top;exit
;;
Free
Free;exit
;;
Quit
Exit
;;
*)
echo "Please input a number: (1-4)."; Exit
Esac
Done
|