標籤:shell select迴圈
學習迴圈,見了很多的for,while,或者until,而select用的比較少,這裡是稍微總結下select這個迴圈。
基本結構:
select VALUE in LIST
do
COMMAND
done
而現實出來的結構大概為值前有個數字,選擇的那個數字,是$REPLY的值,這裡不懂沒事,可以繼續看下面的程式。$PS3變數相當於shell的預設提示符,預設為空白,可以配合select使用。
#!/bin/bash#save $PS3oPS3=$PS3PS3="請選擇喜歡的水果q退出:"select fruit in pear apple banana others quitdo if [ ! -z "$fruit" ] ; then [ "$fruit" == "quit" ] && exit 0 || echo "you choosed $REPLY and you like $fruit" else echo "wrong argv $REPLY" fidone#restore $PS3PS3=$oPS3
執行結果
[[email protected] shell]# ./select.sh 1) pear2) apple3) banana4) others5) quit請選擇喜歡的水果q退出:1you choosed 1 and you like pear請選擇喜歡的水果q退出:6wrong argv 6請選擇喜歡的水果q退出:5
再寫個程式,順便說一下常用的字串到數字運算,自己寫的,有點蹩腳,這個程式要注意有的地方不能有空格比如let,而expr則必須有空格,為了保險,我使用了單引號
#!/bin/bash#save PS3oPS3=$PS3PS3="choose the way:"function way1 (){echo "you are using () to add"tmp1=$((nu1 + nu2))echo "value is $tmp1"}function way2(){echo "you are using expr to add"echo "value is `expr ${nu1} + ${nu2}`"}function way3(){echo "you are using let to add"let tmp2=${nu1}+${nu2}echo "value is $tmp2"}read -p "please input two to test:" nu1 nu2select cal in ‘(())‘ ‘expr‘ ‘let‘ ‘q‘do case $cal in ‘(())‘) way1;; ‘expr‘) way2;; ‘let‘) way3;; ‘q‘) exit 0;; * ) echo "wrong argv";; esacdone#restore PS3PS3=$oPS3
執行結果為
[[email protected] shell]# ./select2.sh please input two to test:2 31) (())2) expr3) let4) qchoose the way:3you are using let to addvalue is 5choose the way:1you are using () to addvalue is 5choose the way:2you are using expr to addvalue is 5choose the way:4
和本次無關
突然想寫這樣一個指令碼
對每一個非系統使用者說聲hello,使用者名稱,i know you are form 使用者組名
我的思路就是shell不能是/sbin/nologin,家目錄不能為/sbin我的檔案時這樣子的
好吧,我承認這個更蹩腳,改天看下詳細的awk命令
#!/bin/bash#change ps2tmp=`cat /etc/passwd`cat /etc/passwd 2>/dev/null|grep -v /sbin/nologin|grep -v /sbin|awk -F ":" ‘{print "hello,"$1",i know you are from "$5"."}‘
執行結果為:
[[email protected] shell]# ./while.sh hello,root,i know you are from root.hello,liuliancao,i know you are from liuliancao.
改天學了awk再修改下吧
這裡有個書上寫的關於變數書寫的tips:
簡寫如下
a)常數,字串,檔案名稱建議大寫
b)數字等資料變數建議小寫
c)命名本質沒有好壞之分,重要的是始終保持一種風格,好像這點我得繼續努力...
本文出自 “啟學的學習之路” 部落格,請務必保留此出處http://qixue.blog.51cto.com/7213178/1656117
shell學習之select迴圈