shell两种循环《一》(小白)

while循环

while循环:
while (条件)
do
动作
done

#!/bin/bash
while :
do
    read -p 'please input your name: ' name
    read -p 'please input your password: ' pwd
    if [ $name = 'batman' ] && [ $pwd = '123' ]
        then
            echo 'login sucessful'
            break #continue
    fi
done
-----------------用户名密码错误---------------------------
please input your name: sb
please input your password: 345
please input your name: dashabi
please input your password: 765
please input your name: jihl
please input your password: 839828
please input your name: 
-------------用户名密码正确-------------------------------
please input your name: batman
please input your password: 123
login sucessful
#!/bin/bash
i=1
while ((i<10))
do
echo $i
((i++))
done
-------------------------输出结果----------------------
[root@bogon ~]# ./b.sh 
1
2
3
4
5
6
7
8
9

for循环

for (变量) in( 列表)
do
动作
done

#!/bin/bash
for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done
-----------------结果----------------------------
[root@bogon ~]# ./f.sh
The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5
--------------例子------------------------------
检查内网存活的IP
#!/bin/bash

for i in {1..254}
do
            (ping -W 1 -c 1 192.168.1.$i &> /dev/null && echo 192.168.1.$i) &
    done

shell中的for常用in列表方式:

for i in 1 2 3
for i in {1,2,3}
for i in {1..9}
for i in {9..1}
for i in {a..z}
for i in {A..Z}
for i in {X..Z}
for i in $(cmd)
for i in $(find ...)

你可能感兴趣的:(shell两种循环《一》(小白))