本文共 1543 字,大约阅读时间需要 5 分钟。
select也是循环的一种,它比较适合用在用户选择的情况下。比如,我们有一个这样的需求,运行脚本后,让用户去选择数字,选择1,会运行w命令,选择2运行top命令,选择3运行free命令,选择4退出。脚本这样实现: #!/bin/bash echo "Please 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 执行结果如下:sh select.shPlease chose a number, 1: run w, 2: run top, 3: run free, 4: quit1) w2) top3) free4) quit#? 116:03:40 up 32 days, 2:42, 1 user, load average: 0.01, 0.08, 0.08USER TTY FROM LOGIN@ IDLE JCPU PCPU WHATroot pts/0 61.135.172.68 15:33 0.00s 0.02s 0.00s sh select.sh#? 3 total used free shared buffers cachedMem: 1020328 943736 76592 0 86840 263624-/+ buffers/cache: 593272 427056Swap: 2097144 44196 2052948#?我们发现,select会默认把序号对应的命令列出来,每次输入一个数字,则会执行相应的命令,命令执行完后并不会退出脚本。它还会继续让我们再次输如序号。序号前面的提示符,我们也是可以修改的,利用变量PS3即可,再次修改脚本如下: #!/bin/bash PS3="Please select a number: " echo "Please 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 如果想要脚本每次输入一个序号后就自动退出,则需要再次更改脚本如下: #!/bin/bash PS3="Please select a number: " echo "Please 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 |
转载于:https://blog.51cto.com/lingjing/1650706