Linux之shell条件判断

本文详细介绍了Linuxshell中if,elif,else和case语句的使用,通过实例展示了如何根据条件执行不同指令,包括单分支、双分支、多分支以及case的多条件判断。涉及了内存检查、用户身份验证、成绩评估、CPU品牌识别和字符类型判断等内容。
摘要由CSDN通过智能技术生成

if语句

单分支

# 语法1:
if <条件表达式>
then
	指令
fi
#语法2:
if <条件表达式>;then
	指令
fi

案例

  • 编写脚本choice1.sh,利用单分支结构实现输入2个整数,判断最大值后输出($符相当于取值符号)
[root@server ~]# vim choice1.sh
#!/bin/bash
read -p "请输入第一个整数: " x
read -p "请输入第二个整数: " y
max=$x
if (($max<$y))
then    
        max=$y
fi      



[root@server ~]# bash choice1.sh
请输入第一个整数:6
请输入第二个整数:3
最大值:6
  • 编写脚本choice3.sh ,判断当前脚本的执行者身份,若不是root账户执行则输出提示,并退出
# 检查当前账户4种方法:
[root@server ~]# whoami
root
[root@server ~]# id -u
0
[root@server ~]# echo $USER
root
[root@server ~]# echo $UID
0
[root@server ~]# vim  choice3.sh
#!/bin/bash
if [ "$USER" != "root" ]
then
        echo "please switch user root"
fi



[root@server ~]# mv  choice3.sh  /  # 移动脚本到根
[root@server ~]# su redhat       # 切换账户身份
[fox@server root]$ cd  /
[fox@server /]$ bash  choice3.sh 
please switch user root

双分支

if <条件表达式>
then
	指令序列1
else
	指令序列2
fi

案例

  • 面试题:编写脚本choice2.sh,使用双分支判断当前系统的剩余内存大小,若低于100M则发送消息进行告警
[root@server ~]# vim  choice2.sh
#!/bin/bash
free_mem=$(free -m | grep Mem | tr -s " " | cut -d " " -f 4)
if (($free_mem<100))
then
        echo "警告,剩余内存为:$free_mem,低于100MB"
else
        echo "剩余内存为:$free_mem,空间足够"
fi



[root@server ~]# bash choice2.sh
剩余内存为:948,空间足够
  • 编写脚本choice4.sh , 实现闰年的判断(闰年:能被4整除但不能被100整除或者能被400整除的年份
[root@server ~]# vim  choice4.sh
#!/bin/bash
read -p "请输入四位数年份:" year
if [ $(($year%4)) -eq 0 ] && [ $(($year%100)) -ne 0 ] || [ $(($year%400)) -eq 0 ]
then
        echo "$year年是润年"
else
        echo "$year年是平年"
fi



[root@server ~]# bash choice4.sh
请输入四位数年份:2018
2018年是平年
[root@server ~]# bash choice4.sh
请输入四位数年份:2024
2024年是润年
  • 编写脚本choice5.sh,判断sshd是否运行
# 分析
# 1.通过分析服务执行的进程数判断
[root@server ~]# ps  -ef | grep  服务名 | grep -v grep | wc -l
# 2.通过查看是否开放端口判断
[root@server ~]# netstat  -lntup | grep 端口号 | wc -l
[root@server ~]# vim choice5.sh
#!/bin/bash
num=$(ps  -ef | grep  sshd | grep -v grep | wc -l)
if (($num>0))
then
        echo  "sshd is running"
else
        echo  "sshd is not running"
fi



[root@server ~]# bash choice5.sh
sshd is not running
  • 编写脚本choice8.sh,检测主机是否存活
[root@server ~]# vim choice8.sh
#!/bin/bash
read -p "请输入测试主机的IP地址:"  ip
ping  -c 2 -w 3 $ip  &> /dev/null
# -c 2 表示发出2个数据包,-w 3表示等待3秒结束,注意:不能等待1秒结束,有可能第二个包未返回就结束会报错
if [ $? -eq 0 ]
then
        echo  "主机$ip已运行"
else
        echo  "主机$ip未运行"
fi



[root@server ~]# bash choice8.sh
请输入测试主机的IP地址:192.168.80.130
主机192.168.80.130未运行
# 上例修改,使用循环测试多台主机,存活的主机显示应用高亮的颜色显示
#!/bin/bash

for ip  in 192.168.48.{125..135}
do
        ping  -c 2 -w 3 $ip  &> /dev/null
        if [ $? -eq 0 ]
        then
                echo  -e "\e[1;31m主机$ip已运行\e[0m"
        else
                echo  "主机$ip未运行"
        fi
done    

多分支

if 条件表达式1
then
	指令序列1
elif 条件表达式2
then
	指令序列2
else
	指令序列n
fi
  • 编写脚本choice6.sh , 输入百分制成绩,判断后输出等级成绩
[root@server ~]# vim choice6.sh
read -p  "请输入百分制成绩: "  score
if [ -z $score ]      
then
        echo  "未输入,请重新输入."
elif  (($score<0 || $score>100 ))
then
        echo  "成绩输入有误,请输入0-100间整数成绩"
elif  (($score >= 90))
then
        echo "成绩优秀"
elif   (($score >=80))
then
        echo  "成绩良好"
elif   (($score>=60))
then
        echo  "成绩及格"
else
        echo  "补考"
fi



[root@server ~]# bash choice6.sh
请输入百分制成绩:
未输入,请重新输入
[root@server ~]# bash choice6.sh
请输入百分制成绩:100
成绩优秀
  • 编写脚本choice7.sh,判断主机的cpu品牌
[root@server ~]# cat /proc/cpuinfo
processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 186
model name      : 13th Gen Intel(R) Core(TM) i7-13620H
stepping        : 2
microcode       : 0x410e
cpu MHz         : 2918.399
cache size      : 24576 KB
physical id     : 0
siblings        : 2
core id         : 0
cpu cores       : 2
apicid          : 0
initial apicid  : 0
fpu             : yes
fpu_exception   : yes
cpuid level     : 32
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon rep_good nopl xtopology tsc_reliable nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves avx_vnni arat umip pku ospke gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize flush_l1d arch_capabilities
bugs            : spectre_v1 spectre_v2 spec_store_bypass swapgs itlb_multihit eibrs_pbrsb
bogomips        : 5836.79
clflush size    : 64
cache_alignment : 64
address sizes   : 45 bits physical, 48 bits virtual
power management:

processor       : 1
vendor_id       : GenuineIntel
cpu family      : 6
model           : 186
model name      : 13th Gen Intel(R) Core(TM) i7-13620H
stepping        : 2
microcode       : 0x410e
cpu MHz         : 2918.399
cache size      : 24576 KB
physical id     : 0
siblings        : 2
core id         : 1
cpu cores       : 2
apicid          : 1
initial apicid  : 1
fpu             : yes
fpu_exception   : yes
cpuid level     : 32
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon rep_good nopl xtopology tsc_reliable nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves avx_vnni arat umip pku ospke gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize flush_l1d arch_capabilities
bugs            : spectre_v1 spectre_v2 spec_store_bypass swapgs itlb_multihit eibrs_pbrsb
bogomips        : 5836.79
clflush size    : 64
cache_alignment : 64
address sizes   : 45 bits physical, 48 bits virtual
power management:

[root@server ~]# grep  "vendor_id"  /proc/cpuinfo
vendor_id       : GenuineIntel
vendor_id       : GenuineIntel


[root@server ~]# vim choice7.sh
#!/bin/bash
vendor=$(grep  "vendor_id"  /proc/cpuinfo | uniq | cut -d " " -f2)
if [ $vendor == GenuineIntel ]
then
        echo  "Inter"
elif [ $vendor == GenuineAMD ]  # AuthenticAMD
then
        echo  "AMD"
else
        echo  "unknow"
fi



[root@server ~]# bash choice7.sh
Inter
  • 编写脚本choice9.sh,根据用户的输入内容,判断是数字、字母、其它字符
[root@server ~]# vim  choice9.sh
#!/bin/bash
read -p  "请输入字母、数字、其它字符: " str
if echo $str | grep [a-zA-Z]  >  /dev/null
then
        echo  "字母"
elif  echo  $str | grep [0-9]  > /dev/null
then
        echo  "数字"
else
        echo  "字符"
fi



[root@server ~]# bash choice9.sh
请输入字母,数字,其他字符:890
数字
[root@server ~]# bash choice9.sh
请输入字母,数字,其他字符:adg
字母
[root@server ~]# bash choice9.sh
请输入字母,数字,其他字符:!@#
字符

case多条件判断

格式

case 变量名 in
	值1)
	 指令1
	;;
	值2)
	 指令2
	;;
	值3)
	 指令3 
	;;
	*)
	默认 
esac      #结束case语句

执行过程

  • case语句会将该变量的值)括号中的值相比较如果与某个值相等,则执行对应语句。
  • 遇到“;;”符号时,就跳出case语句,执行esac语句后面的语句。
  • 如果没有与任何一个值相匹配,则执行*)后面的一组语句

示例

  • 编写脚本choice10.sh,对上例7的百分制成绩判断等级成绩进行改写
[root@server ~]# vim  choice10.sh
#!/bin/bash
read -p "请输入百分制成绩: " score
case $score in
        9[0-9]|100)
                echo "成绩优秀"
        ;;
        8[0-9])
                echo  "成绩良好"
        ;;
        6[0-9]|7[0-9])
                echo  "成绩及格"
        ;;
        *)
                echo  "补考"
esac




[root@server ~]# bash choice10.sh
请输入百分制成绩:99
成绩优秀
[root@server ~]# bash choice10.sh
请输入百分制成绩:9
补考
  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

^~^前行者~~~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值