@if判断之while循环及for循环

一 流程控制之if判断


1、什么是if判断

依据条件的真假来决定是否做事

2、为何要有if判断

为了让计算机能够像人一样去做判断

3、如何用

if 条件1;then

​    代码1

​	代码2

​	.............

elif 条件2;then

​    代码1

​	代码2

...........

elif 条件3;then

​    代码1

​	代码2

.......

else

​    代码1

​	代码2

.........

fi




案例1

#!/bin/bash

echo "start......"
read -p "请输入您的年龄: " age

if [ $age -eq 18 ];then
	echo "too young"
	echo "too young"
	echo "too young"
fi
echo "end......"

案例2

#!/bin/bash

echo "start......"
read -p "请输入您的年龄: " age

if [ $age -eq 18 ];then
	echo "too young"
else
	echo "too old"
fi
echo "end......"

案例3:

#!/bin/bash

read -p "请输入您的分数: " score

if [ $score -ge 90 ];then
    echo "优秀"
elif [ $score -ge 80 ] && [ $score -lt 90 ];then
    echo "良好"
elif [ $score -ge 70 ] && [ $score -lt 80 ];then
    echo "一般" 
else
	echo "很差"
fi

案例4:

#!/bin/bash

read -p "请输入您的分数: " score

if [ $score -ge 90 ];then
    echo "优秀"
elif [ $score -ge 80 ];then
    echo "良好"
elif [ $score -ge 70 ];then
    echo "一般" 
else
	echo "很差"
fi

案例5:

#!/bin/bash

read -p "输入用户名:" inp_user
read -p "输入密码:" inp_pwd

if [ $inp_user = "egon" ] && [ $inp_pwd = "123" ];then
	echo "登录成功"
else
	echo "用户名或者密码错误"
fi
	

二 流程控制之while循环

1、什么是循环

2、为何要循环

3、如何用循环

#!/bin/bash

while true
do
	echo 111
	echo 222
	echo 333
done

案例1

#!/bin/bash

while true
do
    read -p "输入用户名:" inp_user
    read -p "输入密码:" inp_pwd

    if [ $inp_user = "egon" ] && [ $inp_pwd = "123" ];then
        echo "登录成功"
    else
        echo "用户名或者密码错误"
    fi
done	

案例2:

#!/bin/bash

while true
do
    read -p "输入用户名:" inp_user
    read -p "输入密码:" inp_pwd

    if [ $inp_user = "egon" ] && [ $inp_pwd = "123" ];then
        echo "登录成功"
        break
    else
        echo "用户名或者密码错误"
    fi
done

案例3:

# 多行
while 条件
do
	命令1
	命令2
	命令3
done

# 一行
while 条件;do 命令1;命令2;命令3; done

while true;do ifconfig eth0;sleep 0.5;clear; done 

三 流程控制之for循环

案例1

for i in {1..3}
do
    echo ok1 $i
    echo ok2 $i
    echo ok3 $i
done

案例2

for x in "aaa" 2222 "ccc"
do
    echo $x
done

案例3

#!/bin/bash

for i in {2..254}
do
	(
    ping -c1 1.1.1.$i &>/dev/null
    if [ $? -eq 0 ];then
        echo "1.1.1.$i ok"
    else
    	echo "1.1.1.$i down"
    fi
    ) &
done
#测试指定网段的所有ip的状态

案例4:

#!/bin/bash

cd /root/test

for i in `ls`
do
mv $i `ls $i | cut -d "." -f1`.log

done 
#更改指定目录下的文件类型的后缀


案列5:


#!/bin/bash

while true
do
    read -p "(我)我牛逼:" who
    read -p "(你)我也牛逼:" you

    if [ $who = "yes" ] && [ $you = "yes" ];then
       echo "是真牛"
     elif [ $you = "no" ] || [ $who = "yes" ];then
       echo "不行啊"
       echo "你得低调"
       break
     else
       echo "再给你一次机会说"
    fi
done
#自我感觉良好的对话脚本
   看 完了呀
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值