Shell Script Programming Advanced
Process Control
过程式编程语言 顺序执行 选着执行 循环执行
Conditional Select if statement
选择执行注意:if语句可嵌套单分支 if判断条;then 条件为真的分支代码 fi双分支: if判断条件;then 条件为真的分支的代码 else 条件为假的分支代码
If statement
多分支 if 判断条件1; then 条件1为真的分支代码 elif 判断条件2; then 条件2为真的分支代码 elif 判断条件3; then 条件3为真的分支代码 else 以上条件都为假的分支代码 fi逐条件进行判断,第一次遇为“真”条件时,执行其分支,而后结束整个if语句
If example
根据命令的退出状态来执行命令if ping -c1 -W2 station1 &> /dev/null; then echo ‘Station1 is UP‘elif grep "station1" ~/maintenance.txt &> /dev/null; then echo ‘Station1 is undergoing maintenance‘else echo ‘Station1 is unexpectedly DOWN!‘ exit 1fi
Conditional Judgment: Case statement
Cycle
循环执行 将某代码段重复运行多次 重复运行多少次 循环次数事先已知 循环次数事先未知 有进入条件和退出条件for, while, until
For loop
The for variable name in list; Do loop body done for i[i represents the variable name] in {1..10}; "In followed by the list" do Userdel-r user$i; The "Do and do" is the loop body execution mechanism: The elements in the list are assigned to the "variable name" in turn; The loop body is executed once each assignment; Until the element in the list is exhausted, the loop end example: [[email protected]:11:44bin] #sum = 0; For NUM in 1 4 6 4;do Sum=$[sum+num]; Done echo sum= $sum sum=38 [[[Email protected]:12:58bin] #for num in 1 4 6 4;do echo "num= $num";d one num=1 num =23 num=4 num=6 num=4 [[email protected]:13:24bin] #sum = 0; For num in {1..100};d o sum=$[sum+num]; Done echo sum= $sum sum=5050 [[email protected]:16:24bin] #sum = 0; For num in ' seq ';d o sum=$[sum+num]; Done echo sum= $sum sum=55 [[email protected]:16:47bin] #sum = 0; For num in {1..100..2};d o sum=$[sum+num]; Done echo sum= $sum sum=2500 Example: Calculates 1 to 100 and [[email protected]:27:29bin] #sum = 0; For i in {1..100};d o sum=$[sum+i];d one;echo sum= $sum sum=5050 [[email protected]:27:44bin] #sum = 0; For i in ' SEQ 1 2 ';d o sum=$[sum+i];d one;echo sum= $sum sum=2500
For loop
列表生成方式:(1) 直接给出列表(2) 整数列表: (a) {start..end} (b) $(seq [start [step]] end)(3) 返回列表的命令 $(COMMAND)(4) 使用glob,如:*.sh(5) 变量引用; [email protected], $*
While loop
while CONDITION; do
Until cycle
until CONDITION; do 循环体done进入条件: CONDITION 为false退出条件: CONDITION 为true
Loop Control statement Continue
Loop control Statement Break
用于循环体中break [N]:提前结束第N层循环,最内层为第1层 while CONDTIITON1; doCMD1...if CONDITION2; thenbreakfiCMDn... done
Loop Control Shift Command
shift [n]用于将参量列表 list 左移指定次数,缺省为左移一次。参量列表 list 一旦被移动,最左端的那个参数就从列表中删除。while 循环遍历位置参量列表时,常用到 shift./doit.sh a b c d e f g h./shfit.sh a b c d e f g h
Example: doit.sh
#!/bin/bash# Name: doit.sh# Purpose: shift through command line arguments# Usage: doit.sh [args]while [ $# -gt 0 ] # or (( $# > 0 ))do echo $* shiftdone示例:shift.sh#!/bin/bash#step through all the positional parametersuntil [ -z "$1" ]do echo "$1" shiftdoneecho
Create an infinite loop
while true; do循环体doneuntil false; do循环体Done
Shell Script Programming Advanced