bash腳本編程:循環(huán)執(zhí)行
for, while, until
進(jìn)入條件:
for:列表元素非空;
while:條件測(cè)試結(jié)果為“真”
unitl:條件測(cè)試結(jié)果為“假”退出條件:
for:列表元素遍歷完成葵硕;
while:條件測(cè)試結(jié)果為“假”
until:條件測(cè)試結(jié)果為“真”-
循環(huán)控制語(yǔ)句:
-
continue:提前結(jié)束本輪循環(huán)眉抬,而直接進(jìn)入下一輪循環(huán)判斷;
while CONDITION1; do CMD1 ... if CONDITION2; then continue fi CMDn ... done
-
break:提前跳出循環(huán)
while CONDITION1; do CMD1 ... if CONDITION2; then break fi done
-
sleep命令:
?? - delay for a specified amount of time??
sleep NUMBER
練習(xí)
每隔3秒鐘到系統(tǒng)上獲取已經(jīng)登錄用戶的用戶的信息懈凹;其中蜀变,如果logstash用戶登錄了系統(tǒng),則記錄于日志中介评,并退出库北;
[root@localhost ~]# bash /scripts/e16-1.sh
logstash pts/2 2019-03-16 06:13 (192.168.223.1)
[root@localhost ~]# tail /tmp/users.log
logstash login
[root@localhost ~]# cat /scripts/e16-1.sh
#!/bin/bash
while true;do
who | grep logstash
if [ $? -eq 0 ];then
echo "logstash login" >> /tmp/users.log
break
fi
sleep 3
done
while循環(huán)的特殊用法(遍歷文件的行):
while read VARIABLE; do
循環(huán)體;
done < /PATH/FROM/SOMEFILE
示例:找出ID號(hào)為偶數(shù)的用戶们陆,顯示其用戶名寒瓦、ID及默認(rèn)shell;
[root@localhost ~]# bash /scripts/e16-2.sh
root:0:/bin/bash
daemon:2:/sbin/nologin
lp:4:/sbin/nologin
shutdown:6:/sbin/shutdown
mail:8:/sbin/nologin
games:12:/sbin/nologin
ftp:14:/sbin/nologin
systemd-network:192:/sbin/nologin
sshd:74:/sbin/nologin
chrony:998:/sbin/nologin
fedora:4004:/bin/bash
archlinux:4006:/bin/bash
tcpdump:72:/sbin/nologin
saslauth:996:/sbin/nologin
apache:48:/sbin/nologin
haproxy:188:/sbin/nologin
[root@localhost ~]# cat /scripts/e16-2.sh
#!/bin/bash
while read line;do
uid=$(echo $line |cut -d':' -f3)
if [ $[$uid%2] -eq 0 ];then
echo $line |cut -d: -f1,3,7
fi
done < /etc/passwd
for循環(huán)的特殊用法:
for ((控制變量初始化;條件判斷表達(dá)式;控制變量的修正語(yǔ)句)); do
循環(huán)體
done