当前位置:网站首页>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:]]代表大写字母
边栏推荐
猜你喜欢

下午见!2022京东云数据库新品发布会

XDR平台架构与关键技术解析

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

【MySQL功法】第4话 · 和kiko一起探索MySQL中的运算符

87.(cesium之家)cesium热力图(贴地形)

Summary of redis basics - data types (strings, lists, sets, hashes, sets)

第四课 标识符、关键字、变量、变量的分类和作用域、常量

第四周学习 HybridSN,MobileNet V1,V2,V3,SENet

MySQL之json数据操作

Matlab学习13-图像处理之可视化GUI程序
随机推荐
深度学习:文本CNN-textcnn
优维低代码:Provider 构件
Android 技术面试准备(含面试题及答案)
【倒计时5天】探索音画质量提升背后的秘密,千元大礼等你来拿
Dry goods!A highly structured and sparse linear transformation called Deformable Butterfly (DeBut)
【MySQL】数据库进阶之索引内容详解(上篇 索引分类与操作)
How to retrieve IDC research reports?
日常开发写代码原则
[LeetCode—Question 2 Sum of Two Numbers Detailed Code Explanation ] The source code is attached, which can be copied directly
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!...
Generate interface documentation online
LeetCode-1796. 字符串中第二大的数字
零拷贝、MMAP、堆外内存,傻傻搞不明白...
hystrix 服务熔断和服务降级
Analysis of the idea of the complete knapsack problem
微信小程序获取用户手机号码
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?...
进程内存
后台图库上传功能
最牛逼的集群监控系统,它始终位列第一!