1. for循环语句:
for的两种常用写法:
写法(1):
for var in 1 2 3 4 5 (ps:或者for var in $(seq 1 5)或者for var in {1..5}) do echo -n "$val " done
写法(2):
for((i=0;i<10;i++)) ( ps:必须是for(( )) ) { let "val=i%2" if [ $val -ne 0 ]; then echo "${i} is a odd number" fi }
2. while循环语句:
while常用写法:
写法(1):
while read line # ( ps:while读取是按行读,常用于文本按行读取 ) do if [ "$line" -eq 5 ]; then echo "5" break fi done # ( ps:写成 done < data.txt 则重定向从data.txt中按行读取数据)
写法 (2):
res=10 while [ $res -gt 0 ] do echo -n "$res " let "res-=1" done echo "done"