当前位置:网站首页>bash case usage
bash case usage
2022-08-03 11:43:00 【little green head】
bash case usage
In bash scripts, in addition to using if for conditional judgment, you can also use case for conditional judgment.
case can handle many conditions than if else, and the conditions are all matching strings
case format is as follows
case variable inCondition 1)Statement 1statement 2;;Condition 2)Statement 1statement 2;;*)Statement 1statement 2;;escaNote:
- Conditions are all strings, you can use simple bash wildcards such as |, [], etc. The * sign means match all strings
- Double quotes are required at the end of the statement;;
Example
Example 1: Write a script to provide the following menu to the user
m|M) show memory usages; show memory information
d|D) show disk usages; show disk information
q|Q)quit exit
[[email protected] bash_test]# cat 14.sh#!/bin/bashcat << EOFm|M) show memory usages;d|D) show disk usages;q|Q) quitEOFread -p "input you choice " UserChoicecase $UserChoice inm|M)free -m;;d|D)df -h;;q|Q)exit 0;;*)echo "invalid character"esac[[email protected] bash_test]# ./14.shm|M) show memory usages;d|D) show disk usages;q|Q) quitinput you choice Mtotal used free shared buff/cache availableMem: 7812 3227 4086 82 498 4247Note: The option can use | to represent or, for example, input m or M to view memory information
Example 2: Write a program that reads input from the terminal and determines whether the input is a number, lowercase letter, uppercase letter, or special character
[[email protected] bash_test]# cat CheckInput.sh#!/bin/bashread -p "input a character:" Charcase $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.shinput a character:Aa upperNote: [a-z] needs to be placed after [A-Z], because [a-z] includes [A-Z] in bash, but we can also use [[:lower:]] to represent lowercase letters, [[:upper:]]Represents capital letters
边栏推荐
猜你喜欢
随机推荐
Dva.js 新手入门指南
实现2d人物在跳跃的同时左右移动
LeetCode——1161. 最大层内元素和
5个超好用手机开源自动化工具,哪个适合你?
缓存--伪共享问题
bash while循环和until循环
字节最爱问的智力题,你会几道?
Blazor Server(6) from scratch--policy-based permission verification
基于英雄联盟的知识图谱问答系统
GET 和 POST 有什么区别?
QGIS绘制演习区域示意图
899. 有序队列 : 最小表示法模板题
Simple implementation of a high-performance clone of Redis using .NET (1)
零信任架构分析【扬帆】
viewstub 的详细用法_pageinfo用法
bash for loop
深度学习中数据到底要不要归一化?实测数据来说明!
第四课 标识符、关键字、变量、变量的分类和作用域、常量
智能日报脚本
Traceback (most recent call last): File









