文章目录

一 流程控制之if判断

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
else
echo "1.1.1.$i
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
#自我感觉良好的对话脚本
   看 完了呀