04-SHELL循环语句

循环语句

for/do/done:
#FRUIT变量都有apple banana pear,然后遍历输出FRUIT遍历。
#!/bin/bash
for FRUIT in apple banana pear; do
    echo "I like $FRUIT"
done
[root@localhost ~]# ./test.sh 
I like apple
I like banana
I like pear

#把文件名以chap开头的,改成文件名后面+~
[root@localhost ~]# touch chap{1..3}
[root@localhost ~]# for FILENAME in chap?; do mv $FILENAME $FILENAME~; done
[root@localhost ~]# ls | grep cha
chap1~
chap2~
chap3~
while/do/done:
#TRY变量就是用户所输入的内容,如果用户输入的内容不是secret,就输出"Sorry,try again",并且让它在输入,知道内容等于secret为止。
#!/bin/bash
echo "Enter password:"
read TRY
while [ "$TRY" != "secret" ]; do
    echo "Sorry,try again"
    read TRY
done
[root@localhost ~]# ./test.sh 
Enter password:
secret
[root@localhost ~]# ./test.sh 
Enter password:
123.com
Sorry,try again
123.com
Sorry,try again
secret

#控制循环的次数,定义COUNTER变量为1,每循环一遍COUNTER就会增加1,直到COUNTER大于等于10时停止循环。
#!/bin/bash
COUNTER=1
while [ "$COUNTER" -lt 10 ]; do
    echo "Here we go again"
    COUNTER=$(($COUNTER+1))
done
[root@localhost ~]# ./test.sh 
Here we go again
Here we go again
Here we go again
Here we go again
Here we go again
Here we go again
Here we go again
Here we go again
Here we go again
break和continue:
  • break n可以指定跳出几层循环;
  • continue:跳过本次循环,但不会跳出循环,continue n可以指定跳过几层循环。
  • 即break跳出,continue跳过。
#如果COUNTER的值等于五,则输出"Sorry,Permission denied"且不进行输入变量,跳过循环。
#!/bin/bash
echo "Enter Password:"
COUNTER=0
read TRY
while [ "$TRY" != "secret" ]; do
    COUNTER=$(($COUNTER+1))
    if [ $COUNTER -eq 5  ]
    then
        echo "Sorry,Permission denied"
        break
    else
        echo "Sorry,try again"
        read TRY
    fi
done
echo "identity varified"
[root@localhost ~]# ./test.sh 
Enter Password:
123.com
Sorry,try again
123.com
Sorry,try again
123.com
Sorry,try again
123.com
Sorry,try again
123.com
Sorry,Permission denied
identity varified
[root@localhost ~]# ./test.sh 
Enter Password:
secret
identity varified

你可能感兴趣的:(SHELL快速复习专用,python,java,shell,c语言,linux)