四、其他控制語句
1.case分支格式:
case 變數值 in
模式1)
命令序列1 ;; 模式2) 命令序列2 ;; …… * ) 默認執行的命令序列 esac
2.until循環語句格式:
until 條件測試命令 do 命令序列 done
3.shift遷移語句 遷移位置變數,將 $1~$9 依次向左傳遞
4,break語句 在for、while、until等循環語句中,用於跳出當前所在的循環體,執行循環體后的語5,continue 在for、while、until等循環語句中,用於跳過循環體內餘下的語句,重新判斷條件以便執行下一次循環句 由用戶從鍵盤輸入一個字元,並判斷該字元是否為字母、數字或者其他字元,並輸出相應的提示信息. [root@localhost ~]# vi hitkey.sh #!/bin/bash read -p "ress some key, then press Return: " KEY case "$KEY" in [a-z] | [A-Z]) echo "It's a letter." ;; [0-9]) echo "It's a digit." ;; *) echo "It's function keys,spacebar or other keys. " esac [root@localhost ~]# sh hitkey.sh Press some key, then press Return: K It's a letter. [root@localhost ~]# sh hitkey.sh Press some key, then press Return: 6 It's a digit. [root@localhost ~]# sh hitkey.sh Press some key, then press Return: ^[[19~ //按F8鍵 It's function keys,spacebar or other keys.
編寫一個shell程序,計算多個整數值的和,需要計算的各個數值由用戶在執行腳本時作為命令行參數給出. [root@localhost ~]# vi sumer.sh #!/bin/bash Result=0 while [ $# -gt 0 ] do Result=`expr $Result $1` shift done echo "The sum is : $Result" [root@localhost ~]# chmod a x sumer.sh [root@localhost ~]# ./sumer.sh 12 34 The sum is : 46
循環提示用戶輸入字元串,並將每次輸入的內容保存到臨時文件“/tmp/input.txt”中,當用戶輸入“END”字元串時退出循環體,並統計出input.txt文件中的行數、單詞數、位元組數等信息,統計完后刪除臨時文件. [root@localhost ~]# vi inputbrk.sh #!/bin/bash while true do read -p "Input a string: " STR echo $STR >> /tmp/input.txt if [ "$STR" = "END" ] ; then break fi done wc /tmp/input.txt rm -f /tmp/input.txt [root@localhost ~]# sh inputbrk.sh Input a string: wandogn Input a string: dongdonga Input a string: END 3 3 22 /tmp/input.txt
刪除系統中的stu1~stu20各用戶賬號,但stu8、stu18除外. [root@localhost ~]# vi delsome.sh #!/bin/bash i=1 while [ $i -le 20 ] do if [ $i -eq 8 ] || [ $i -eq 18 ] ; then let i continue fi userdel -r stu$i let i done [root@localhost ~]# sh delsome.sh [root@localhost ~]# grep "stu" /etc/passwd stu8:531:531::/home/stu8:/bin/bash stu18:541:541::/home/stu18:/bin/bash
五、Shell函數應用
1,語法
function 函數名 {
命令序列 } 或者: 函數名() { 命令序列 } 在腳本中定義一個help函數,當用戶輸入的腳本參數不是“start”或“stop”時,載入該函數並給出關於命令用法的幫助信息,否則給出對應的提示信息. [root@localhost ~]# vi helpfun.sh #!/bin/bash help() { echo "Usage: "$0" start|stop" } case "$1" in start) echo "Starting ..." ;; *) help esac [root@localhost ~]# chmod a x helpfun.sh [root@localhost ~]# ./helpfun.sh start Starting ... [root@localhost ~]# ./helpfun.sh restart Usage: ./helpfun.sh start|stop
在腳本中定義一個加法函數,用於計算兩個數的和,並調用該函數分別計算12 34、56 789的和. [root@localhost ~]# vi adderfun.sh #!/bin/bash adder() { echo `expr $1 $2` } adder 12 34 adder 56 789 [root@localhost ~]# sh adderfun.sh 46 845