5 Bash Case Statement Examples

Linux Shell 脚本编程实战 >>从语法到运维案例 Shell 本质:调用 Linux 系统命令,语法只负责控制命令执行逻辑。学习路线:变量 → 判断 → 循环 → 函数 → 数组 → sed/awk 三剑客。写脚本思路梳理业务需求,拆解执行步骤先命令行调试单条命令,确认输出符合预期封装变量、函数,完成脚本编写边界测试:参数为空、文件不存在、命令执行失败等场景企业实战要求:能够编写巡检、备份、部署、监控脚本,读懂线上数百行自动化脚本。 阅读详情

Bash shell case statement is similar to switch statement in C. It can be used to test simple values like integers and characters.

Case statement is not a loop, it doesn’t execute a block of code for n number of times. Instead, bash shell checks the condition, and controls the flow of the program.

In this article let us review the bash case command with 5 practical examples.

The case construct in bash shell allows us to test strings against patterns that can contain wild card characters. Bash case statement is the simplest form of the bash if-then-else statement.

Syntax of bash case statement.

case expression in
    pattern1 )
        statements ;;
    pattern2 )
        statements ;;
    ...
esac

Following are the key points of bash case statements:

  • Case statement first expands the expression and tries to match it against each pattern.
  • When a match is found all of the associated statements until the double semicolon (;;) are executed.
  • After the first match, case terminates with the exit status of the last command that was executed.
  • If there is no match, exit status of case is zero.

Bash Case Example 1. Sending Signal to a Process

The following script accepts the signal number and process id as it’s arguments, and sends the signal to a given process id using signal name.

This script is to demonstrate the usage of the case statement.

$ cat signal.sh
#!/bin/bash

if [ $# -lt 2 ]
then
        echo "Usage : $0 Signalnumber PID"
        exit
fi

case "$1" in

1)  echo "Sending SIGHUP signal"
    kill -SIGHUP $2
    ;;
2)  echo  "Sending SIGINT signal"
    kill -SIGINT $2
    ;;
3)  echo  "Sending SIGQUIT signal"
    kill -SIGQUIT $2
    ;;
9) echo  "Sending SIGKILL signal"
   kill -SIGKILL $2
   ;;
*) echo "Signal number $1 is not processed"
   ;;
esac

In the above example:

  • $1 and $2 are the signal number and process id respectively.
  • Using kill command, it sends the corresponding signal to the given process id.
  • It executes the sleep command for a number of seconds.
  • The optional last comparison *) is a default case and that matches anything.

Usage of the above shell script: Find out the process id of the sleep command and send kill signal to that process id to kill the process.

$ sleep 1000

$ ps -a | grep sleep
23277 pts/2    00:00:00 sleep

$ ./signal.sh 9 23277
Sending SIGKILL signal

$ sleep 1000
Killed

Also, refer to our earlier kill article – 4 methods to kill a process.

Bash Case Example. 2. Pattern Match in a File

This example prints the number of lines,number of words and delete the lines that matches the given pattern.

$ cat fileop.sh
#!/bin/bash

# Check 3 arguments are given #
if [ $# -lt 3 ]
then
        echo "Usage : $0 option pattern filename"
        exit
fi

# Check the given file is exist #
if [ ! -f $3 ]
then
        echo "Filename given \"$3\" doesn't exist"
        exit
fi

case "$1" in

# Count number of lines matches
-i) echo "Number of lines matches with the pattern $2 :"
    grep -c -i $2 $3
    ;;
# Count number of words matches
-c) echo "Number of words matches with the pattern $2 :"
    grep -o -i $2 $3 | wc -l
    ;;
# print all the matched lines
-p) echo "Lines matches with the pattern $2 :"
    grep -i $2 $3
    ;;
# Delete all the lines matches with the pattern
-d) echo "After deleting the lines matches with the pattern $2 :"
    sed -n "/$2/!p" $3
    ;;
*) echo "Invalid option"
   ;;
esac

Execution of the above script is shown below.

$ cat text
Vim is a text editor released by Bram Moolenaar in 1991 for the Amiga computer.
The name "Vim" is an acronym for "Vi IMproved" because Vim was created as an extended version of the vi editor, with many additional features designed to be helpful in editing program source code.
Although Vim was originally released for the Amiga, Vim has since been developed to be cross-platform, supporting many other platforms.
It is the most popular editor amongst Linux Journal readers.

Bash case regex output. After deleting the lines matches with the pattern Vim:

$ ./fileop.sh  -d Vim text
It is the most popular editor amongst Linux Journal readers.

Also, refer to our earlier article on Bash ~ expansaion and { } expansion.

Bash Case Example 3. Find File type from the Extension

This example prints type of a file (text, Csource, etc) based on the extension of the filename.

$ cat filetype.sh
#!/bin/bash
for filename in $(ls)
do
	# Take extension available in a filename
        ext=${filename##*\.}
        case "$ext" in
        c) echo "$filename : C source file"
           ;;
        o) echo "$filename : Object file"
           ;;
        sh) echo "$filename : Shell script"
            ;;
        txt) echo "$filename : Text file"
             ;;
        *) echo " $filename : Not processed"
           ;;
esac
done

$ ./filetype.sh
a.c : C source file
b.c : C source file
c1.txt : Text file
fileop.sh : Shell script
obj.o : Object file
text : Not processed
t.o : Object file

Bash Case Example 4. Prompt User with Yes or No

In most of the software installation, during license agreement, it will ask yes or no input from user. The following code snippet is one of the way to get the yes or no input from user.

$ cat yorno.sh
#!/bin/bash

echo -n "Do you agree with this? [yes or no]: "
read yno
case $yno in

        [yY] | [yY][Ee][Ss] )
                echo "Agreed"
                ;;

        [nN] | [n|N][O|o] )
                echo "Not agreed, you can't proceed the installation";
                exit 1
                ;;
        *) echo "Invalid input"
            ;;
esac

$ ./yorno.sh
Do you agree with this? [yes or no]: YES
Agreed

If there are several patterns separated by pipe characters, the expression can match any of them in order for the associated statements to be run. The patterns are checked in order until a match is found; if none is found, nothing happens.

Also, refer to our earlier 15 bash array examples article.

Bash Case Example 5. Startup script

Startup scripts in the /etc/init.d directory uses the case statement to start and stop the application.

You can use any kind of patterns, but its always recommended to use case statement, when you’re testing on values of primitives. (ie. integers or characters).

$ cat startpcapp
#!/bin/bash

case "$1" in
'start')
echo "Starting application"
/usr/bin/startpc
;;
'stop')
echo "Stopping application"
/usr/bin/stoppc
;;
'restart')
echo "Usage: $0 [start|stop]"
;;
esac

$ ./startpcapp start
Starting application
/usr/bin/startpc started
http://www.thegeekstuff.com/2010/07/bash-case-statement/
Shell 入门指南:从基础语法到实战脚本 Shell是用户与操作系统交互的命令行解释器,常见如Bash、Zsh。通过编写Shell脚本可实现自动化任务,如文件处理、日志清理等。脚本使用变量、条件判断、循环、函数及重定向功能,结合set -euo pipefail提升健壮性,配合shellcheck静态检查与注释优化,能高效编写可靠脚本。掌握基础语法后,从日常任务入手,逐步构建实用自动化工具。 阅读详情

相关推荐

如何使用apifox打包测试用例生成测试套件自动化执行

使用apifox打包测试用例生成测试套件自动化执行

weixin_55613512的博客 2886

Terraform故障排查四层模型:语法、执行、依赖与环境层诊断

Terraform并非单纯配置语言,而是一个多层级基础设施编排引擎。其错误本质源于HCL解析、Provider执行、模块依赖和运行环境四个正交层面的交互失效。理解语法层(如`Invalid expression`)的静态校验机制、执行层(含AWS/Azure/GCP API响应码)的动态调用链、依赖层(`module.output`空值、资源循环)的数据流完整性,以及环境层(`xkbcomp`、Python路径、时区、BOM头等系统级干扰),是实现精准排障的前提。该分层模型支撑起从`terraform va

hqmln的博客 481

基于单片机控制的开关电源设计

采用开关电源技术和MCU模块,凭借可靠性高、易于调适的特点,可以更高效地发挥出二者的优势,从而实现更好的组合。stm32的起动模式是通过Boot0和Boot1两个管脚的高低电平来决定的,当stm32被供电之后,这两个管脚的电平。在 VCC上,键盘的一头(列线)被连接到 VCC上,而在“0”的编程输出中,则用来进。,在开关管打开的情况下,由输入电力供给电流,感应装置存储   Buck变换器是一种非隔离式的电压转换器[10]整流电路对输入电压进行整流,再经过滤波电路,即Dc电压是直流/直流变换器的直流输入。

QQ1694456187的博客 2309

CANN/runtime:昇腾NPU运行时组件

- [2026/4] Added support for Ascend 950PR/Ascend 950DT chips. Continuously enhanced AclGraph functionality, optimized documentation structure, and improved developer experience. - [2025/12] The runtim

gitblog_00256的博客 1127

劳特巴赫 Trace32 调试使用教程

详细介绍如何使用trace32进行调试

m0_56208280的博客 4万+

LCD驱动芯片——BL55072A驱动程序

初始化子程序: START 0x7C; I2C子地址 0xEA;ICSET,软件复位芯片 0xC0;MODSET,关显示 0xF0;BLKCTL,关闪烁 0xA3;DISCTL,80Hz Line inversion,High Power mode 0xE8;ICSET,清复位bit1 STOP 显示刷新子程序: START 0x7C;I2C子地址 0xF0;BLKCTL,关闪烁 0xA3;DISCTL,80Hz Line inversion,High Power mode 0xE8或0xEC;ICSE

love421的博客 3176

go test command

go test 是 Go 用来执行测试函数(test function)、基准函数(benchmark function)和示例函数(example function)的命令。执行 go test 命令,它会在*_test.go文件中寻找 test、benchmark 和 example 函数来执行。测试函数名必须以 TestXXX 开头,基准函数名必须以 BenchmarkXXX 开头,示例函数必须以 ExampleXXX 开头。// test 测试函数// benchmark 基准函数。

Doublelv 的博客专栏。 6272

DO-254标准详解:航空电子硬件设计保证指南全方位解析

RTCA DO-254, 也被称为《机载电子硬件设计保证指南》,是航空电子硬件设计和验证中的关键标准,旨在为确保机载电子硬件的安全性提供设计保证。自2000年首次发布以来,DO-254就成为了民航和军用飞机中电子硬件设计认证的基准文件。随着航空硬件技术的进步和日益复杂化,确保硬件设计的准确性、可靠性和安全性变得至关重要。本标准是由RTCA和EUROCAE共同开发的,适用于涉及机载硬件的航空公司、飞机制造商、供应商和认证机构。

qq_41854911的博客 3682

vscode 的tab与空格设置 ,vscode使用sftp配置 ,vscode代码补全插件

vscode默认就是一个tab=4个空格,若想要修改请进入seting里面设置。3.也可以选择:将缩进转换为制表符,然后保存即可。目前使用shell-format。目前使用Clang格式化风格。

喜欢打篮球的普通人 1万+

手把手教你学Simulink--基于未来出行解决方案的场景实例:电动飞行汽车(eVTOL)的动力系统建模与仿真

电动垂直起降飞行器零道路拥堵:三维空间飞行绿色低碳:全电驱动,零排放快速响应:城市内15分钟直达低噪音:相比直升机↓20dB📊 预测:2030年全球eVTOL市场规模将超300亿美元,中国、美国、欧洲加速适航认证。本文通过,构建了电动飞行汽车(eVTOL)动力系统高压电池系统建模电力电子(DC-DC、逆变器)实现PMSM电机+螺旋桨推进系统搭建完整飞行任务动态仿真性能KPI评估与优化。

MHD0815的博客 443

[Dify]-进阶5- 使用 Dify 构建多轮对话的客服机器人

本文介绍了如何利用Dify平台构建智能客服系统,重点阐述了ChatFlow框架的应用。系统支持多轮对话、业务接口集成和话术策略管理,具备订单查询、退货申请等核心功能。通过Classifier节点实现意图识别,借助Router节点分流处理流程,并结合API插件实现业务数据对接。文章还提供了部署调试、会话优化和监控分析的具体方法,强调模块化设计和插件化集成的重要性,为构建功能完善的智能客服系统提供了完整解决方案。

技术小甜甜:传播可落地技术,帮助个人和企业降低解决真实场景问题的成本 1660

工作中使用到的单词(软件开发)

1.エイリアス   alias 别名 powershell使用 get-help 命令时,会得到与此命令 相关(别名)的命令 2.プロキシ proxy 代 理 3.プロモート   promote 促进,提升   开发的系统新功能上线发布,有时会使用到这个词,比如 STプロモート 还有使用リリース这个词的。比如STリリース。个人认为两者含义相同。 4.見逃し み................................................................

sun0322 6万+

元宇宙通证- 九、IT/ICT发展史全景长图

九、IT/ICT发展史全景长图 (一)综述 IT是Information Technology的缩写,意为”信息技术“,包含现代计算机、网络、通信等信息领域技术。自1844年人类历史上发出来第一份电报,实现了信息的长图传输,信息技术发展的历史大幕随之拉开。信息技术的普遍应用,是进入信息社会的标志。 IT技术最早发源于半导体,然后发展处计算机、通信网和互联网,进而演进到现在的AI、XR、计算机、大数据、物联网、工业互联网、区块链、量子计算等。 有人说元宇宙是下一代互联网,有人说元宇宙是互联网的终极形态。 我们

沧海之巅的专栏 1万+

Apache2 Bash CGI:动态时间页面与请求验证

1. 服务介绍 CGI 让 Apache 执行服务端程序并将输出作为 HTTP 响应。本文用固定 Bash 脚本输出系统时间,说明响应头后的空行、模块与执行权限;不接受用户输入或拼接系统命令。 2. 准备运行环境 UOS/Debian 系 Apache2、Bash、管理员配置权限及隔离测试站点。先确认 Apache MPM 和现有虚拟主机,不将整个上传目录开

weixin_44524357的博客 243

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

Linux Bash 常用操作与历史参数复用

……

u013669912的博客 354

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

certbot certificates 报错:-bash: certbot: command not found

certbot certificates 报错:-bash: certbot: command not found

weixin_52173250的博客 315

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

Linux 进程控制:fork、exit、wait、exec 与手写一个 mini shell

讲清进程控制的四个动作:fork 创建(内核四件事与写时拷贝)、exit/_exit/return 终止与 8 位退出码、wait/waitpid 等待与 status 位图、exec 七接口与唯一系统调用 execve,最后用这些零件拼出一个支持 cd/export/echo 的 mini shell,并解释环境变量两张表与 putenv 浅拷贝坑。附速查表与 14 道自测题。

BIII__的博客 189

第一章 Shell 概述

本文介绍了Shell编程的基础知识,包括Shell的起源与发展、常见Shell类型及查看方式,阐述了Shell作为命令解释器连接用户与操作系统内核的作用。强调其作为解释型脚本语言的优势,适用于系统管理自动化任务。内容涵盖Shell脚本基本结构、注释规范、编写风格、执行方法及常用命令(如echo、printf、history、管道等),并讲解了命令执行顺序、退出状态码等核心概念,为初学者提供系统学习路径。

sbjdhjd的博客 304

DeepAgents框架构建一个带有严格安全护栏的本地 Shell 执行环境。

核心亮点在于:通过精心设计的 System Prompt(系统提示词)强制约束大模型的行为,防止其通过操作系统底层的 Shell 命令绕过框架的虚拟沙箱,从而确保本地物理磁盘的绝对安全。DeepAgents 框架接入 DeepSeek 模型并构建一个带有严格安全护栏的本地 Shell 执行环境。

qq_42092076的博客 71

Linux、Shell、MySQL 测试卷逐题细讲(下篇:MySQL)

本文为Linux、Shell、MySQL测试卷下半段MySQL部分逐题讲解,包含填空、选择与SQL分析三类题型。填空题覆盖COUNT、HAVING、DISTINCT、事务、约束、索引等核心语法;选择题辨析存储过程、索引类型、ACID、存储引擎、用户管理等考点。SQL大题围绕员工、部门、职位、地点四张关联表,考察多表连接、分组聚合、自连接、相关子查询、NULL处理等高频写法,标注LEFT JOIN统计计数、NULL判断、子查询别名等易错坑点,同时梳理试卷OCR识别带来的干扰问题,重点提示SQL实操中的常见失误

dongziwen1的博客 185

miniconda3设置为shell终端默认激活环境

将以下内容添加至 ~/.bashrc,路径需根据实际修改(如 /home/jason/miniconda3): # >>>conda initialize >>> __conda_setup="$('/home/jason/miniconda3/bin/conda' 'shell.bash' 'hook' 2>/dev/null)" if [ $? -eq 0 ]; then eval "$__conda_setup" else if [ -f "/home/jason/miniconda3/etc/pro

huangjiazhi_的博客 207

CST如何通过Shell Solid or Thicken Sheet对模型进行挖空及加厚

在CST建模中,ShellSolid可对实体模型挖空,形成壁厚为指定值的封闭或开放壳体,通过选择不同面可控制开口位置;ThickenSheet则用于将无厚度二维片体加厚为三维实体。操作时需在导航树中选中模型,调用ShapeTools中的相应功能,设置厚度并预览确认。两者结合可高效实现复杂结构建模,适用于电磁仿真前处理。

a18665053298的博客 135

抖音_libsscronet_证书校验绕过

代理(Reqable)进行中间人后换发的证书,系统信任库是认的,但还要过这层自定义校验:最终落到 Java 的。,纯 Python 标准库,不需要 IDA / Ghidra / capstone。是安装时随机生成的,每台设备、每次重装都不同,换设备或重装后需重新查一次并替换。so 已被映射进运行中的进程,覆盖磁盘不会影响内存里的旧映像,不杀进程等于没改。,抖音所有网络请求的底层,自带 BoringSSL(同目录。关掉开关后,回调根本不执行,下面的 JNI、,Python 3.6+,仅用标准库。

qq_44990881的博客 182

论开发与应用的差异--以office利用与MySQL安装设置为例

本文对比了传统Excel数据绑定Word生成通知的模板化操作与现代前后端开发中数据库驱动页面渲染的差异。早期依赖Excel(容量有限)实现批量生成,现发展为用数据库替代Excel,通过前端绑定数据实现动态页面渲染,形成前后端分离模式。以淘宝初期招聘为例,强调页面开发能力的重要性。同时指出,掌握MySQL、Workbench、Shell等数据库相关工具及概念,是专业开发能力的关键,需熟练运用报告中涉及的所有技术术语,以弥补与Office操作的差距。

mewowaBc的博客 148
上一篇: bash 参数(一)
下一篇: shell脚本和case 使用相关的例子
liufei_learning
博客等级 码龄17年 821粉丝 145原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值