shell腳本(10)-流程式控制制while
一、while循環介紹
while循環與for一樣,一般不知道循環次數使用for,不知道循環的次數時推薦使用while
二、while語法
while [ condition ] #條件為真才會循環,條件為假,while停止循環
do
commands
done
三、while實戰
1、使用while遍歷文件內容
#!/usr/bin/bash
while read i
do
echo "$i"
done < $1
查看運行結果:
[root@localhost test20210728]# sh while-1.sh /etc/passwd root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin sync:x:5:0:sync:/sbin:/bin/sync shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown halt:x:7:0:halt:/sbin:/sbin/halt
......
2、while實現賬戶登錄判斷
[root@localhost test20210728]# vim while-2.sh
#!/usr/bin/bash
read -p "login: " account
while [ $account != 'root' ]
do
echo "輸入的賬戶不符合條件,請重新輸入:"
read -p "login: " account
done
查看運行結果:
[root@localhost test20210728]# sh while-2.sh
login: test
輸入的賬戶不符合條件,請重新輸入:
login: root1
輸入的賬戶不符合條件,請重新輸入:
login: root
[root@localhost test20210728]#
3、while+sleep(輸出1-10,且每次輸出後睡眠1s)
[root@localhost test20210728]# vim while-3+sleep.sh
#!/usr/bin/bash
i=1
while [ $i -lt 10 ];do
echo -n $i" "
sleep 1
i=$((i+1))
done
echo
查詢運行結果:(每秒輸出一個數字)
[root@localhost test20210728]# sh while-3+sleep.sh
1 2 3 4 5 6 7 8 9
4、while+break(輸出1開始自增,且到5時停止)
[root@localhost test20210728]# vim while-4+break.sh
#!/usr/bin/bash
i=1
while [ $i -lt 10 ];do
echo -n $i" "
if [ $i -eq 5 ];then
break
fi
i=$((i+1))
done
echo
查看運行結果:
[root@localhost test20210728]# sh while-4+break.sh
1 2 3 4 5
5、while+continue(輸出1-10開始自增,且到5時跳過輸出)
[root@localhost test20210728]# vim while-5+continue.sh
#!/usr/bin/bash
i=0
while [ $i -lt 10 ];do
i=$((i+1))
if [ $i -eq 5 ];then
continue
fi
echo -n $i" "
done
echo
查看運行結果:
[root@localhost test20210728]# sh while-5+continue.sh
1 2 3 4 6 7 8 9 10