學習linux的菜鳥 shell指令碼中的迴圈
阿新 • • 發佈:2021-11-03
學習linux的菜鳥
shell指令碼中的迴圈
常用到的迴圈有for迴圈和while迴圈。
- for迴圈
[root@localhost sbin]# cat for.sh #! /bin/bash for i in `seq 1 5`; do echo $i done
指令碼中的seq15
表示從1到5的一個序列。你可以直接執行這個命令試下。指令碼執行結果為:
[root@localhost sbin]# sh for.sh 1 2 3 4 5
通過這個指令碼就可以看到for迴圈的基本結構:
for 變數名 in 迴圈的條件; do command done
這裡的 “迴圈的條件” 可以寫成一組字串或者數字(用1個或者多個空格隔開), 也可以是一條命令的執行結果:
[root@localhost sbin]# for i in 1 2 3 a b; do echo $i; done 1 2 3 a b
也可以寫引用系統命令的執行結果,就像那個seq15
但是需要用反引號括起來:
[root@localhost sbin]# for file in `ls`; do echo $file; done case.sh first.sh for.sh if1.sh if2.sh if3.sh option.sh read.sh sum.sh variable.sh
- while迴圈
[root@localhost sbin]# cat while.sh #! /bin/bash a=5 while [ $a -ge 1 ]; do echo $a a=$[$a-1] done
while 迴圈格式也很簡單:
while 條件; do command done
上例指令碼的執行結果為:
[root@localhost sbin]# sh while.sh 5 4 3 2 1
另外你可以把迴圈條件拿一個冒號替代,這樣可以做到死迴圈,常常這樣寫監控指令碼:
while :; do command sleep 3 done
shell指令碼中的函式
函式就是把一段程式碼整理到了一個小單元中,並給這個小單元起一個名字,當用到這段程式碼時直接呼叫這個小單元的名字即可。
有時候指令碼中的某段程式碼總是重複使用,如果寫成函式,每次用到時直接用函式名代替即可,這樣就節省了時間還節省了空間
[root@localhost sbin]# cat func.sh #! /bin/bash function sum() { sum=$[$1+$2] echo $sum } sum $1 $2
執行結果如下:
[root@localhost sbin]# sh func.sh 1 2 3
func.sh中的 sum() 為自定義的函式,在shell指令碼函式的格式為:
function 函式名() { command }
在shell指令碼中,函式一定要寫在最前面,不能出現在中間或者最後,因為函式是要被呼叫的,如果還沒有出現就被呼叫,肯定是會出錯的