Shell 编程的流程控制 if case while until for select

Shell 编程的流程控制


  • 1、if 判断分支结构
  • 2、case判断分支结构

  • 1、流程控制while循环
  • 2、流程控制until循环(了解)
  • 3、流程控制之for循环
  • 3、流程控制之select(了解)
  • 4、函数
    • 1、函数的基本使用:先定义,后调用
    • 2、函数的参数
    • 3、函数的返回值
    • 4、作用域

流程控制之if判断

1.单分支

if 条件1;then
    命令1
    命令2
    命令3
    。。。
fi

# 等同于:
[ 条件1 ] && 命令1 
``
示例1:检测硬盘根分区的使用率,如果大于70,就输出警告信
```python
#!/bin/bash

# 第一步:获取硬盘的使用率
disk_use=`df | grep '/' |awk '{print5}' | cut -d% -f1`
# 第二步:
if [ $disk_use -gt 70 ];then
    echo "Warning:disk space is not enough"
fi

示例2:

===========================版本1===========================
#!/bin/bash

grep "^root" /etc/passwd &>/dev/null
if [ $? -eq 0 ];then
    echo "Y"
else
    echo "N"
fi
===========================版本1===========================
#!/bin/bash

if grep "^root" /etc/passwd &>/dev/null;then
    echo "Y"
else
    echo "N"
fi

2.双分支

if 条件1;then
    命令1
    命令2
    命令3
    。。。
else
    命令1
    命令2
    命令3
    。。。 
fi

# 等同于:
[ 条件1 ] && 命令1 || 命令2

示例

#!/bin/bash

read -p "用户名>>: " name
read -p "密码>>: " pass

if [ name == "egon" ] && [pass == "123" ];then
    echo "登录成功"
else
    echo "账号或密码输入错误"
fi

3.多分支

if 条件1;then
    命令1
    命令2
    命令3
    。。。
elif 条件2;then
    命令1
    命令2
    命令3
    。。。
elif 条件2;then
    命令1
    命令2
    命令3
    。。。 
...
else
    命令1
    命令2
    命令3
    。。。 
fi

示例1

#!/bin/bash

#1、获取硬盘根分区的使用率
disk_use=`df | grep '/' |awk '{print5}' | cut -d% -f1`

#2、根据比较输出不同级别的日志
if [ disk_use -ge 90 ];then  # >=90
    echo "Critical:disk space is full"
elif [disk_use -ge 70 -a disk_user -lt 90 ];then  # >=70 <90
    echo "Error:disk space will be full"
elif [disk_use -ge 50 -a $disk_user -lt 70 ];then  # >=50 < 70
    echo "Warning:disk space is not enough"
else
    echo "info:disk space is ok"
fi

==============================改进===========================

#!/bin/bash

#1、获取硬盘根分区的使用率
#disk_use=`df | grep '/' |awk '{print5}' | cut -d% -f1`
#disk_use=99
#disk_use=73
#disk_use=53
disk_use=30

#2、根据比较输出不同级别的日志
if [ disk_use -ge 90 ];then  # >=90
    echo "Critical:disk space is full"
elif [disk_use -ge 70 ];then  # >=70 <90
    echo "Error:disk space will be full"
elif [ $disk_use -ge 50 ];then  # >=50 < 70
    echo "Warning:disk space is not enough"
else
    echo "info:disk space is ok"
fi

示例2

#!/bin/bash

[ # -ne 1 ] && echo "必须输入1个参数" && exit
[[ !1 =~ ^[0-9]+]] && echo "必须输入数字" && exit

if [1 -gt 18 ];then
    echo "too big"
elif [ $1 -lt 18 ];then
    echo "too small"
else
    echo "you got it"
fi

示例

#!/bin/bash

[ # -ne 1 ] && echo "必须输入1个参数" && exit

if [ -L1 ];then
    echo "是一个链接文件"
elif [ -d 1 ];then
    echo "是一个目录文件"
elif [ -f1 ];then
    echo "是一个标准文件"
else
    echo "其他类型的文件"
fi

示例4:检测80端口是否开启,未开启则开启

#!/bin/bash

netstat -an | grep '\bLISTEN\b' | grep '\b80\b' &>/dev/null
if [ ? -eq 0 ];then
    echo "80端口的服务正常"
else
    systemctl start httpd &>/dev/null
    if [? -eq 0 ];then
        echo "80端口启动成功"
    else
        echo "80端口启动失败"
    fi    
fi

示例5:编写监控脚本

实现:

根分区剩余空间小于10%
内存的剩余空间小于30%
向用户egon发送告警邮件,邮件的内容包含使用率相关信息

#!/bin/bash

# 1、获取根分区的剩余空间
disk_use=`df | grep '/' | awk '{print5}' | cut -d% -f1`

# 2、获取内存的剩余率
mem_free=`free | grep 'Mem' |awk '{print 4}'`
mem_total=`free | grep 'Mem' |awk '{print2}'`
mem_free_percent=`echo "scale=2;mem_free /mem_total" |bc |cut -d. -f2`

# 3、判断+报警
if [ disk_use -gt 90 ];then
    echo "硬盘使用率{disk_use}%,不够用啦,请及时处理" | mail -s "磁盘报警" 18611453110@163.com
fi

if [ mem_free_percent -lt 30 ];then
    echo "内存剩余率{mem_free_percent}%,不够用啦,请及时处理" | mail -s "内存报警" 18611453110@163.com
fi

ps:发送报警邮件

[root@egon day04]# mail -s "标题" root <<< "要爆炸啦"
[root@egon day04]# echo "邮件的内容" | mail -s "标题" root

# 应用
[root@egon day04]# echo "内存不够用啦,请及时处理" | mail -s "报警邮件" 18611453110@163.com
You have new mail in /var/spool/mail/root
[root@egon day04]# hostname  # 注意主机名的格式
egon.xxx.com

case语句

case 变量名 in
值1)
    命令1
    命令2
    命令3
    ;;
值2)
    命令1
    命令2
    命令3
    ;;
值3)
    命令1
    命令2
    命令3
    ;;
*)
    命令1
    命令2
    命令3
esac


# 类似
if [变量名 == 值1 ];then
    命令1
    命令2
    命令3
elif [ 变量名 == 值2 ];then
    命令1
    命令2
    命令3
elif [变量名 == 值3 ];then
    命令1
    命令2
    命令3
else
    命令1
    命令2
    命令3
fi

示例1:测试用户身份

#!/bin/bash

read -p "请输入你的用户名: " name
case $name in
"root")
    echo "超级管理员"
    ;;
"egon")
    echo "VIP用户"
    ;;
"tom")
    echo "SVIP用户"
    ;;
*)
    echo "其他用户"
esac

示例2:nginx管理脚

#!/bin/bash

if [ # -ne 1 ];then
    echo "Usage:0 {start|stop|reload|status}"
    exit 1
fi

case 1 in
"start")
    netstat -an |grep 'LISTEN' |grep '\b80\b' &>/dev/null
    if [? -eq 0 ];then
        echo "nginx already start"
    else
        # /usr/local/nginx/sbin/nginx
        systemctl start nginx &>/dev/null
        if [ ? -eq 0 ];then
            echo "nginx start ok"
        else
            echo "nginx start failed"
        fi
    fi
    ;;
"stop")
    # /usr/local/nginx/sbin/nginx -s stop
    systemctl stop nginx &>/dev/null
    if [? -eq 0 ];then
       echo "nginx stop ok"
    else
       echo "nginx stop failed"
    fi
    ;;
"reload")
    # /usr/local/nginx/sbin/nginx -s reload
    systemctl reload nginx &>/dev/null
    if [ ? -eq 0 ];then
       echo "nginx reload ok"
    else
       echo "nginx reload failed"
    fi
    ;;
"status")
    netstat -an |grep 'LISTEN' |grep '\b80\b' &>/dev/null    if [? -eq 0 ];then
       echo "nginx is up"
    else
       echo "nginx is down"
    fi
    ;;
*)
   echo "Usage:$0 {start|stop|reload|status}"
esac

ps

[root@egon day04]# . /etc/init.d/functions 
[root@egon day04]# action "nginx start ok" true
nginx start ok                                             [  OK  ]
[root@egon day04]# action "nginx start ok" false
nginx start ok                                             [FAILED]
[root@egon day04]# 

while循环

问题代码

#!/bin/bash

read -p "用户名:" name
read -p "密码:" pass

if [ name == "egon" ] && [pass == "123" ];then
    echo "login successful"
else
    echo "user or password error"
fi

read -p "用户名:" name
read -p "密码:" pass

if [ name == "egon" ] && [pass == "123" ];then
    echo "login successful"
else
    echo "user or password error"
fi

read -p "用户名:" name
read -p "密码:" pass

if [ name == "egon" ] && [pass == "123" ];then
    echo "login successful"
else
    echo "user or password error"
fi

while循环语法:

while循环可以命名为条件循环

# 条件为true就执行循环体代码,条件变为false循环结束
while 条件
do
    命令1
    命令2
    命令3
    ...
done

#示例
#!/bin/bash

count=0

while [ count -lt 5 ]  # 5<5
do
    echocount 
    let count++  # 5
done

until 循环

# 条件为false就执行循环体代码,条件变为true循环结束
until 条件
do
    命令1
    命令2
    命令3
    ...
done

# 示例
#!/bin/bash

count=0

until [ count -eq 5 ]   
do
    echocount 
    let count++  # 5
done

结束循环

break:立即终止本层循环

continue:终止本次循环

#!/bin/bash

count=0

while [ count -lt 5 ]  # 1<5
do
    if [count -eq 3 ];then
        # break
        let count++
        continue
    fi
    echo $count 
    let count++  # 3
done

总结:结束while循环的两种方案

在循环体代码中把某个值改掉,让条件变为假

[root@egon day05]# cat test.sh 
#!/bin/bash

count=0
while [ $count -lt 3 ]
do
    echo 1111
    count=100
    echo 2222
    echo 3333

done
[root@egon day05]# ./test.sh 
1111
2222
3333
[root@egon day05]

break

[root@egon day05]# cat test.sh 
#!/bin/bash

count=0
while [ $count -lt 3 ]
do
    echo 1111
    #count=100
    break
    echo 2222
    echo 3333

done
[root@egon day05]# ./test.sh 
1111
[root@egon day05]# 

了解

# break结束嵌套多层的循环
while 条件1
do
    while 条件2
    do
        while 条件3
        do
            break 3
        done
        # break
    done
    # break
done


# 把条件改为false
tag=true
while tag
do
    whiletag
    do
        while $tag
        do
            tag=false
        done
    done
done

重写登录认证=》版本1

#!/bin/bash

while true
do
    read -p "用户名:" name
    read -p "密码:" pass

    if [ name == "egon" ] && [pass == "123" ];then
        echo "login successful"
        break
    else
        echo "user or password error"
    fi
done


重写登录认证=》版本2

[root@egon day05]# cat login_new.sh 
#!/bin/bash

tag=true
while tag
do
    read -p "用户名:" name
    read -p "密码:" pass

    if [name == "egon" ] && [ $pass == "123" ];then
        echo "login successful"
        #tag=false
        break
    else
        echo "user or password error"
    fi

    # echo "===========>"
done

[root@egon day05]# 

写一个验证身份并执行命令的脚本

#!/bin/bash

while true
do
    read -p "用户名:" name
    read -p "密码:" pass

    if [ name == "egon" ] && [pass == "123" ];then
        echo "login successful"

        while true
        do
            read -p "[root@egon ------->]# " cmd
            if [ cmd == "q" ];then
                break
            ficmd
        done
        break
    else
        echo "user or password error"
        # continue  # 不要画蛇添足
    fi
done

测试网站能否正常访问,wget访问出错三次就结束并发送报警信息

[root@egon day05]# cat check_web.sh 
#!/bin/bash

[ # -ne 1 ] && echo "只能输入一个参数" && exit

url=1
count=0

while true
do
    echo "=========>count"
    if [count -eq 3 ];then
        echo "报警:url is dead"
        break
    fi

    wget --timeout=1 --tries=3url -q
    if [ ? -eq 0 ];then
        echo "url is ok"
        break
    else
    let count++        
    fi
done
[root@egon day05]# 

[root@egon day05]# ./check_web.sh 
只能输入一个参数
[root@egon day05]# ./check_web.sh www.baidu.com
=========>0
www.baidu.com is ok
[root@egon day05]# ./check_web.sh www.egon.com.cn
=========>0
=========>1
=========>2
=========>3
报警:www.egon.com.cn is dead
[root@egon day05]# 

while从文件中读取一行行内容来进行循环

[root@egon day05]# cat 6.sh
#!/bin/bash

while read line
do
    echo $line
done < a.txt
[root@egon day05]# ./6.sh 
11111 1:1 1
22222
3333
4444
[root@egon day05]# 

动态监测系统状态

[root@egon ~]# while :;do free;sleep 0.5;clear;done

for 循环

可以将for循环称之为取值循环

语法:shell风格

for i in 值1 值2 值3
do
    echo $i
done

示例1

[root@egon day05]# cat 7.sh 
#!/bin/bash

for i in "aaa" 222 "ccc"
do
    echo $i
done
[root@egon day05]# 

示例2

[root@egon day05]# cat 8.sh 
#!/bin/bash

for i in `ls /scripts/day05`
do
    mv i{i/txt/sh}
done
[root@egon day05]# 

示例3

#!/bin/bash

for i in {5..1}
do
   echo i
done

for i in {a..z}
do
   echoi
done

示例4

#!/bin/bash

for i in {1..254}
do
    ping -c1 10.0.0.i &>/dev/null
    [? -eq 0 ] && echo 10.0.0.$i
done

示例5

#!/bin/bash

for i in {1..3}
do
    命令1
    命令2
    命令3
done 

语法:C风格

#!/bin/bash

for ((i=0;i<3;i++))
do
    echo "命令1"
    echo "命令2"
    echo "命令3"
done

break与continue在for循环中的应用

[root@egon day05]# cat 9.sh 
#!/bin/bash

for i in {A..Z}
do
   if [ i == "C" ];then
     # break
     continue
   fi
   echoi
done
[root@egon day05]# 

练习:统计文件夹下所有的文件类型

#!/bin/bash

[ # -ne 1 ] && echo "必须传入一个参数" && exit

regular=0
dir=0
link=0
other=0

for fname in `ls1`
do
    if [ -L "1/fname" ];then
        let link++
    elif [ -f "1/fname" ];then
        let regular++
    elif [ -d "1/fname" ];then
        let dir++
    else
         let other++
    fi
done

echo "标准文件个数:regular"
echo "目录文件个数:dir"
echo "软连接文件个数:link"
echo "其他文件个数:other"
Copyright © 2009 - Now . XPBag.com . All rights Reserved.
夜心的小站 » Shell 编程的流程控制 if case while until for select

提供最优质的资源集合

立即查看 了解详情