shell第三天,if,for.

if判断

写法
if [ 条件 ]
then
执行语句
elif**[条件]**
执行语句
else
执行语句
fi
例:当变量$1大于$2的时候,输出$1>$2,同理输出当小于时,等于时的结果

[root@compute ~]# vim test.sh
#!/bin/bash
if [ $1 -gt $2 ];then
        echo "$1>$2"
elif [ $1 -lt $2 ];then
        echo "$1<$2"
else
        echo "$1=$2"
fi
[root@compute ~]# bash test.sh 1 2
1<2
[root@compute ~]# bash test.sh 2 1
2>1
[root@compute ~]# bash test.sh 1 1
1=1

for循环

写法
for var in value1 value2 valu3…(循环次数取决于有多少个value)
do
执行命令
done
例:利用循环输出1-5

[root@compute ~]# vim test.sh 
#!/bin/bash
for i in 1 2 3 4 5
        do
                echo "$i"
done
[root@compute ~]# bash test.sh 
1
2
3
4
5

例:利用循环倒计时10秒

[root@compute ~]# vim test.sh 
#!/bin/bash
for((i=10;i>=0;i--))  #这里利用了双括号,双括号里面可以运行算数
        do
                echo "倒计时:$i 秒"
                sleep 1   #这里表示停顿1秒再执行
done
[root@compute ~]# bash test.sh 
倒计时:10 秒
倒计时:9 秒
倒计时:8 秒
倒计时:7 秒
倒计时:6 秒
倒计时:5 秒
倒计时:4 秒
倒计时:3 秒
倒计时:2 秒
倒计时:1 秒
倒计时:0 秒
[root@compute ~]#

跳过本次循环 continue。当执行本次循环遇到continue会跳出本次循环执行下次
例:输出1,2,3,5,6,7,8,9,10,其中不输出4

[root@compute ~]# vim test.sh  
#!/bin/bash
for i in `seq 1 10`  #这里的seq 1 10 要用反引号,这是命令
        do
                if [ $i -eq 4 ];then  #到i=4的时候执行continue跳过本次循环
                        continue
                fi
                echo $i
done
[root@compute ~]# bash test.sh 
1
2
3
5
6
7
8
9
10

结束循环break
例:输入字符,当输入为q的时候退出

[root@compute ~]# vim test.sh  
#!/bin/bash
for ((;;))
        do
                read -p "输入字符:" ch  #读取输入的字符赋给变量ch
                if [ $ch == "q" ];then
                break
                fi
done
[root@compute ~]# bash test.sh 
输入字符:r
输入字符:f
输入字符:ds
输入字符:s
输入字符:q
[root@compute ~]# 
发布了10 篇原创文章 · 获赞 4 · 访问量 1604

猜你喜欢

转载自blog.csdn.net/qq_32502263/article/details/104395899