shell基础 - 03
一 流程控制之if判断
1、什么是if判断
依据条件的真假来决定是否做事
2、为何要有if判断
为了让计算机能够像人一样去做判断
3、如何用
if 条件1;then
代码1
elif 条件2;then
代码1
…
else
代码1
代码2
代码3
fi
案例1
[root@mm count]# cat 1.sh
#!/bin/bash
while true;
do
read -p "请输入当前登录的用户名" username
read -p "请输入当前登录的密码" passwd
if [ $username = "egon" ] && [ $passwd = "123" ];then
echo "登录成功"
break
else
echo "登录失败"
fi
done
案例2
#!/bin/bash
echo "start......"
read -p "请输入您的薪资: " money
if [ $money -eq 18000 ];then
echo "ok"
else
echo "no"
fi
echo "end......"
案例3:
[root@mm count]# cat aa.sh
#! /bin/bash
while true
do
read -p "Linux 12期毕业薪资" money
if [ $money -ge 20000 ];then
echo "哇塞"
break
elif [ $money -ge 15000 ];then
echo "十分优秀"
break
elif [ $money -ge 10000 ];then
echo "还是蛮不错"
break
else
echo "继续努力"
fi
done
案例4:
[root@mm count]# cat ab.sh
# ! /bin/bash
for i in {2..254}
do
echo $i
done
二 流程控制之while循环
1、什么是循环
2、为何要循环
3、如何用循环
#!/bin/bash
while true
do
echo 123
echo 321
done
案例1:
[root@mm count]# cat 1.sh
#!/bin/bash
while true;
do
read -p "请输入当前登录的用户名" username
read -p "请输入当前登录的密码" passwd
if [ $username = "egon" ] && [ $passwd = "123" ];then
echo "登录成功"
break
else
echo "登录失败"
fi
done
案例2:
# 多行
while 条件
do
命令1
命令2
命令3
done
# 一行
while 条件;do 命令1;命令2;命令3; done
while true;do ifconfig eth1;sleep 1;clear; done
三 流程控制之for循环
案例1
[root@mm count]# cat ping.sh
#!/bin/bash
for i in {2..254}
do
(
ping -c1 10.10.0.$i &>/dev/null
if [ $? -eq 0 ];then
echo "10.10.0.$i up"
else
echo "10.10.0.$i down"
fi
)&
done
案例2
for i in 22 "cc" 123
do
echo $i
done
案例3
[root@mm count]# cat zhuji.sh
#! /bin/bash
hostnamectl set-hostname $1
sed -i "s#125#$2#g" /etc/sysconfig/network-scripts/ifcfg-eth0
sed -i "s#125#$2#g" /etc/sysconfig/network-scripts/ifcfg-eth1
systemctl restart network