Skip to main content

loop

for loop
for i in var1 var2 var3; do echo $i; done
for ((i=1;i<=10;i++)); do echo $i; done
for i in $(ls *.log); do echo $i; done  

for t in {1..10};do  echo $t; done
1
2
3
4
5
6
7
8
9
10

for t in {1..10..2};do  echo $t; done
1
3
5
7
9

## 列出目前資料夾的所有目錄名稱
for dir in */;do echo "${dir%/}"; done
while loop

 

## 讀取檔案內容
cat tables_name.lst | while read sch tab;do
> echo "export to $tab.ixf of ixf messages export_$tab.msg select * from $sch.$tab"
> done

## while loop 的應用
## 每 3 秒監看 /worktmp 的磁碟使用狀況
while true;do
> df -h | grep /worktmp
> sleep 3
> done

## 管理 DB2 時常用
while read s t;do
> db2 "select count(*) from $s.$t"
> done < tables.lst > count-tables.out

## 如果是 CSV
while IFS=, read s t;do
> db2 "select count(*) from $s.$t"
> done < tables.csv > count-tables.out

## 迴圈計數 Loop Counter
x=1
while [ $x -le 5 ]
do
  echo "Welcome $x times"
  x=$(( $x + 1 )) 或者 x=$[$x + 1]
done