Linux case语句用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | case 命令 case 语句与 if - then - else 语句的区别。 例1: if - then - else 语句,比较繁琐 [19:37:32 root@libin3 libin] # usermod -G root student [19:22:33 root@libin3 libin] # vim shell55 [19:37:32 root@libin3 libin] # cat shell55 #!/bin/bash # look for a value # if [ $USER = root ] then echo "the user is root" elif [ $USER = student ] then echo "the user is student" elif [ $USER = rhce ] then echo "the user is student" elif [ $USER = helloword ] then echo "the user is helloword" else echo "sorry,no a user exist" fi [19:26:24 root@libin3 libin] # chmod u+x shell55 [19:26:31 root@libin3 libin] # ./shell55 the user is root [student@libin3 libin]$ sudo chmod g+x shell55 [student@libin3 libin]$ . /shell55 the user is student case 命令,就不需要写 elif 语句检查同一个变量值。 case 命令会采用下面的列表格式来检查单个变量的多个值。 格式: case variable in pattern1 | pattern2) commands1;; pattern3) commands2;; *) default commands;; esac case 命令会将指定的变量与不同模式进行比较。如果变量和模式是匹配的,那么shell会执行 为该模式指定的命令。通过 | 操作符在一行中分隔出多各模式。 * 号会捕获所有与已知模式不匹配的值,就相当于 else 。 例2:将例1的语句转换成 case 语句 示例1: [19:48:36 root@libin3 libin] # vim shell56 #!/bin/bash #using the case command # case $USER in root | student) echo "the is $USER" ;; rhce) echo "the is rhce" ;; student) echo "the is student" ;; helloword) echo "the is helloword" ;; *) echo "no is user" ;; esac [19:52:16 root@libin3 libin] # chmod +x shell56 [19:53:11 root@libin3 libin] # ./shell56 the is root 示例2: [19:56:00 root@libin3 libin] # su - student [student@libin3 libin]$ sudo chmod g+x /libin/libin/shell56 [student@libin3 libin]$ . /shell56 the is student 例3:这里我们可以得出 case 语句判断出了libin3.com 为主机名 [21:11:43 root@libin3 libin] # echo $HOSTNAME libin3.com [21:11:45 root@libin3 libin] # vim shell57 #!/bin/bash # using the case command # case $HOSTNAME in libin2.com | libin4.com ) echo "the is $HOSTNAME" ;; libin5.com | libin3.com ) echo "the hostname is libin5.com or $HOSTNAME" ;; libin6.com) echo "the hostname is libin6.com" ;; *) echo "no HOSTNAME" ;; esac [21:04:47 root@libin3 libin] # chmod u+x shell57 [21:05:02 root@libin3 libin] # ./shell57 the hostname is libin5.com or libin3.com |
分类:
Linux shell 类
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下