当前位置:网站首页>bash case用法
bash case用法
2022-08-03 11:34:00 【小青头】
bash case用法
在bash脚本中,除了使用if做条件判断,也可以使用case做条件判断。
case比起if else可以处理条件很多,而且条件均为匹配字符串
case格式如下
case 变量 in
条件1)
语句1
语句2;;
条件2)
语句1
语句2;;
*)
语句1
语句2;;
esca
注意:
- 条件都是字符串,可以使用|,[],等简单的bash通配符,*号代表匹配所有字符串
- 语句结束需要双引号;;
示例
示例1:写一个脚本提供如下菜单显示给用户
m|M) show memory usages;显示内存信息
d|D) show disk usages;显示磁盘信息
q|Q) quit退出
[[email protected] bash_test]# cat 14.sh
#!/bin/bash
cat << EOF
m|M) show memory usages;
d|D) show disk usages;
q|Q) quit
EOF
read -p "input you choice " UserChoice
case $UserChoice in
m|M)
free -m;;
d|D)
df -h;;
q|Q)
exit 0;;
*)
echo "invalid character"
esac
[[email protected] bash_test]# ./14.sh
m|M) show memory usages;
d|D) show disk usages;
q|Q) quit
input you choice M
total used free shared buff/cache available
Mem: 7812 3227 4086 82 498 4247
注意:选项可以使用|代表或,比如输入m或M都可以查看内存信息
示例2:写一个程序,从终端中读取输入,判断输入的是数字,小写字母,大写字母,还是特殊字符
[[email protected] bash_test]# cat CheckInput.sh
#!/bin/bash
read -p "input a character:" Char
case $Char in
[0-9])
echo "a digit";;
[A-Z])
echo "a upper";;
[a-z])
echo "a lower";;
[[:punct:]])
echo "A punction.";;
*)
echo "Special char";;
esac
[[email protected] bash_test]# ./CheckInput.sh
input a character:A
a upper
注意:[a-z]需要放在[A-Z]后面,因为bash中[a-z]包括[A-Z],不过我们也可以使用[[:lower:]]代表小写字母,[[:upper:]]代表大写字母
边栏推荐
- Babbitt | Metaverse daily must-read: Players leave, platforms are shut down, and the digital collection market is gradually cooling down. Where is the future of the industry?...
- Matlab学习10-图像处理之傅里叶变换
- 【MySQL功法】第2话 · 数据库与数据表的基本操作
- Traceback (most recent call last): File
- 缓存--伪共享问题
- 最牛逼的集群监控系统,它始终位列第一!
- Skills required to be a good architect: How to draw a system architecture that everyone will love?What's the secret?Come and open this article to see it!...
- 「全球数字经济大会」登陆 N 世界,融云提供通信云服务支持
- Classical Architecture and Memory Classification of Embedded Software Components
- ThreadLocal源码解析及使用场景
猜你喜欢
![[Star Project] Little Hat Plane Battle (9)](/img/e3/c7d2728080bcdccc181a7e5c50ee6f.png)
[Star Project] Little Hat Plane Battle (9)

【JS 逆向百例】某网站加速乐 Cookie 混淆逆向详解

通过组策略安装软件和删除用户配置文件

Why is the new earth blurred, in-depth analysis of white balls, viewing pictures, and downloading problems

微信小程序获取用户手机号码

缓存--伪共享问题

Matlab学习10-图像处理之傅里叶变换

2022年五面蚂蚁、三面拼多多、字节跳动最终拿offer入职拼多多

使用.NET简单实现一个Redis的高性能克隆版(一)

Analysis of the idea of the complete knapsack problem
随机推荐
LeetCode——1161. 最大层内元素和
微信为什么使用 SQLite 保存聊天记录?
ThreadLocal源码解析及使用场景
谷歌研究员被群嘲:研究员爆料AI有意识,被勒令休假
[论文阅读] (23)恶意代码作者溯源(去匿名化)经典论文阅读:二进制和源代码对比
Matlab学习12-图像处理之图像增强
899. 有序队列 : 最小表示法模板题
ABAB-740新语法
距LiveVideoStackCon 2022 上海站开幕还有3天!
智能合约是什么?
微信小程序获取用户手机号码
【一起学Rust】Rust的Hello Rust详细解析
码率vs.分辨率,哪一个更重要?
LeetCode——622.设计循环队列
请问应该用什么关键字将内容主题设置为 dark 呢
基于PHP7.2+MySQL5.7的回收租凭系统
【JDBC以及内部类的讲解】
云原生 Dev0ps 实践
build --repot
Summary of redis basics - data types (strings, lists, sets, hashes, sets)