1. 程式人生 > 其它 >shell迴圈: for in 和while

shell迴圈: for in 和while

參考:

https://blog.csdn.net/wzj_110/article/details/86669426(for in 用法總結)

迴圈for in,基於列表

語法:

for 變數名  in  列表
do
    command
    command
    ...
done

數字類迴圈

1,seq在in後面的應用

#!/bin/bash  
#也是產生等差數列-->預設是1
for i in $(seq 1 10)  #產生的是一個字串,預設IFS是以空格隔開!
do   
   
done 

2,{}在in後面的應用

total=0 #全域性變數
for i in {1..100} #
".."表示連續,預設也是IFS為空格隔開 do ((total+=i)) done echo -e "total is:${total}"

字元類迴圈

1,普通字串

#!/bin/bash  
list="Linux Java C++ Python"  
for i in $list  
do  
    echo -e "Language is ${i}"   
done 

補充:
echo -n //不換行輸出
echo -e  //處理特殊字元輸出 參考:https://blog.csdn.net/qq_37595946/article/details/77962963

2,cat在in後面的使用

逐行讀取檔案的內容(預設是IFS),所以預設不是逐行列印!

IFS的說明

bash shell會將下列字元當作欄位分隔符:空格、製表符、換行符
說明:如果在shell在資料中看到這些字元中的任意一個,它就會假定這表明了列表中一個新資料欄位的開始!
可以指定多個IFS字元

如果想逐行原樣輸出

#!/bin/bash
# reading content from a file
file="日誌檔案.sh"
#將這個語句加入到指令碼中,告訴bash shell在資料值中忽略空格和製表,使其只能識別換行符!
IFS=$'\n'
for std in $(cat $file)
do
     echo 
"$std" done

3,路徑查詢

ls在in後面的命令

#!/bin/bash  
for i in `ls`;  #ls可以結合統配符應用!
do   
    echo $i is file name\!;  #注意:\的應用!
done  

迴圈while,基於條件

語法

while condition
do
    command
done

#無線迴圈
while :
do
    command
done

while true
do
    command
done

for (( ; ; ))

跳出迴圈

#跳出後續所有迴圈
break 

#只跳出單次迴圈
continue 

#新增次數
break 2
continue 2