Shell 中的 Globbing:原理、使用方法与实现解析(中英双语)

Shell 中的 Globbing:原理、使用方法与实现解析

在 Unix Shell(如 Bash、Zsh)中,globbing 是指 文件名模式匹配(filename pattern matching),它允许用户使用特殊的通配符(wildcards)来匹配多个文件,而不需要手动列出所有文件名。这一功能是 Shell 解析命令时的一个重要步骤,极大地提高了命令行操作的灵活性。


1. 什么是 Globbing?

Globbing 是 Shell 解释用户输入的命令时,将包含通配符的模式 扩展为符合匹配规则的文件名列表 的过程。例如:

ls *.txt

在执行 ls *.txt 时,Shell 不会将 *.txt 直接传递给 ls,而是会 先解析 *.txt 并匹配当前目录下的所有 .txt 文件,然后把结果传递给 ls 命令。例如,当前目录下有:

file1.txt file2.txt file3.log

则:

ls *.txt

实际上等价于:

ls file1.txt file2.txt

其中 file3.log 因不符合 *.txt 的模式匹配规则而被排除。


2. Globbing 的常见通配符

Shell 的 globbing 机制支持多种 通配符(wildcards),常见的有以下几种:

通配符作用示例匹配内容
*匹配 任意数量 的字符(包括 0 个字符)*.txta.txtb.txttest.txt
?匹配 任意单个字符file?.txtfile1.txtfile2.txt,但不匹配 file10.txt
[abc]匹配 [] 内的 任意一个字符file[12].txtfile1.txtfile2.txt
[a-z]匹配 某个范围内的字符file[a-z].txtfilea.txtfileb.txt
{a,b,c}匹配 逗号分隔的任意一个模式file{1,2,3}.txtfile1.txtfile2.txtfile3.txt
** (仅 Bash 4.0+)递归匹配所有子目录**/*.txt匹配当前目录及所有子目录中的 .txt 文件

3. Globbing 的执行流程

在 Shell 处理用户输入的命令时,globbing 是命令解析(parsing)过程中的一个步骤。执行流程如下:

  1. 用户输入命令(例如 ls *.txt)。
  2. Shell 解析命令
    • 如果命令行包含通配符(如 *),Shell 进入 globbing 处理
    • Shell 读取当前目录下的文件列表,并 匹配符合规则的文件名
  3. Shell 替换通配符模式
    • *.txt 被替换为所有匹配的文件名,如 file1.txt file2.txt
  4. Shell 执行最终命令
    • ls file1.txt file2.txt

注意:如果没有任何文件匹配通配符模式,大多数 Shell 会直接返回原始模式,如:

echo *.xyz

如果 *.xyz 没有匹配的文件,Bash 会直接输出 *.xyz,而不会报错。


4. Globbing 与 正则表达式 的区别

Globbing 并不是正则表达式,它们有以下主要区别:

特性Globbing正则表达式
作用文件名匹配处理文本模式匹配
* 含义匹配 任意字符(包括空字符)匹配 前一个字符 0 次或多次
? 含义匹配 任意单个字符匹配 前一个字符 0 或 1 次
. 含义作为普通字符匹配代表 任意单个字符

示例:

ls *.txt    # 使用 globbing,匹配所有 .txt 结尾的文件
grep 'a.*b' file.txt   # 使用正则表达式,匹配 'a' 到 'b' 之间的任何字符

5. 禁用 Globbing

有时候,我们希望 Shell 不要 自动展开通配符,而是让命令接收到原始的 *? 等字符。可以使用以下方法:

  1. 使用单引号 ''
    echo '*.txt'  # 输出 *.txt,而不是匹配的文件列表
    
  2. 使用 set -f 关闭 globbing
    set -f
    echo *.txt   # 直接输出 *.txt
    set +f       # 重新开启 globbing
    

6. Shell 中的 Globbing 实现

Globbing 在 Shell 内部是如何实现的呢?主要分为以下几步:

  1. 读取命令:Shell 读取用户输入的命令字符串。
  2. 解析通配符
    • 遍历当前目录文件列表。
    • 依次对文件名进行 模式匹配(Pattern Matching)。
    • 使用 字符串匹配算法 进行匹配,如:
      • * 进行贪心匹配(Greedy Match)。
      • ? 进行单字符匹配。
      • [a-z] 进行范围匹配。
  3. 替换匹配项
    • 匹配的文件列表替换原始通配符字符串。
  4. 执行命令:Shell 执行替换后的命令。

Shell 通常使用 系统调用 opendir()readdir() 访问目录并进行匹配。


7. 编写 C 代码实现简单的 Globbing

下面是一个使用 fnmatch() 函数进行 Shell 风格模式匹配的 C 代码示例:

具体原理和代码解析请看笔者的另一篇博客: 深入解析 fnmatch():C 语言中的模式匹配函数(中英双语)

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <fnmatch.h>void list_matching_files(const char *pattern) {struct dirent *entry;DIR *dir = opendir(".");if (!dir) {perror("opendir");return;}while ((entry = readdir(dir)) != NULL) {if (fnmatch(pattern, entry->d_name, 0) == 0) {printf("%s\n", entry->d_name);}}closedir(dir);
}int main() {list_matching_files("*.c");  // 匹配当前目录下的所有 .c 文件return 0;
}

运行示例

$ gcc globbing.c -o globbing
$ ./globbing
main.c
utils.c
shell.c

8. 结论

Globbing 是 Shell 解析命令的重要步骤,主要用于 文件名匹配,其实现涉及 字符串匹配算法、系统目录读取 等技术。用户可以利用 通配符 灵活地批量操作文件,但要注意它与 正则表达式 的区别。此外,用户可以通过 单引号set -f 禁用 Globbing,使 Shell 直接传递原始字符串。理解 Globbing 的原理可以帮助我们更高效地使用 Shell 命令,提高自动化任务的执行效率。


这篇博客详细介绍了 Globbing 的概念、用法、实现原理、C 代码示例,希望能帮助你更深入地理解这个 Shell 机制! 🚀

Shell Globbing: Principles, Usage, and Implementation

Globbing in Unix Shell (such as Bash, Zsh) refers to filename pattern matching, where users can use special wildcard characters to match multiple files without manually listing their names. This feature enhances the flexibility of command-line operations.


1. What is Globbing?

Globbing is the process where the Shell expands wildcard patterns into matching filenames before executing a command.

For example, consider the command:

ls *.txt

Instead of passing *.txt as an argument to ls, the Shell first expands the pattern by searching for files in the current directory that match the pattern. If the directory contains:

file1.txt file2.txt file3.log

then the command:

ls *.txt

is actually executed as:

ls file1.txt file2.txt

while file3.log is ignored because it does not match *.txt.


2. Common Wildcards in Globbing

Shell globbing supports several wildcards for flexible pattern matching:

WildcardDescriptionExampleMatches
*Matches any number of characters (including none)*.txta.txt, b.txt, test.txt
?Matches any single characterfile?.txtfile1.txt, file2.txt (not file10.txt)
[abc]Matches any single character in bracketsfile[12].txtfile1.txt, file2.txt
[a-z]Matches any character in the rangefile[a-z].txtfilea.txt, fileb.txt
{a,b,c}Matches any of the comma-separated patternsfile{1,2,3}.txtfile1.txt, file2.txt, file3.txt
** (Bash 4.0+)Recursively matches files in subdirectories**/*.txtAll .txt files in the directory tree

3. How Globbing Works Internally

When a user enters a command, Shell processing follows these steps:

  1. User inputs a command (e.g., ls *.txt).
  2. Shell scans for wildcards:
    • If a command argument contains a wildcard (*, ?, etc.), Shell performs globbing.
    • It retrieves the list of files in the current directory.
    • It matches filenames against the pattern.
  3. Shell replaces the pattern with matching filenames:
    • If *.txt matches file1.txt file2.txt, the final command becomes:
      ls file1.txt file2.txt
      
  4. Shell executes the command.

Note: If no files match, some shells return the original pattern (e.g., echo *.xyz outputs *.xyz).


4. Difference Between Globbing and Regular Expressions

Globbing is not the same as regular expressions. Key differences:

FeatureGlobbingRegular Expressions
PurposeMatches filenamesMatches text patterns
*Matches any charactersMatches previous character zero or more times
?Matches one characterMatches previous character zero or one time
.Treated as a normal characterMatches any character

Example:

ls *.txt         # Uses globbing to list all .txt files
grep 'a.*b' file.txt  # Uses regex to match 'a' followed by 'b'

5. Disabling Globbing

To prevent Shell from expanding wildcards, use:

  1. Single quotes (''):
    echo '*.txt'  # Outputs *.txt without expansion
    
  2. Disable globbing with set -f:
    set -f
    echo *.txt   # Outputs *.txt
    set +f       # Re-enables globbing
    

6. How Globbing is Implemented in Shell

Internally, globbing is handled in these steps:

  1. Shell reads the command string.
  2. Pattern matching against directory contents:
    • It retrieves files using system calls like opendir() and readdir().
    • It applies pattern matching algorithms.
  3. Matches are substituted before executing the command.

7. Implementing Globbing in C

The following C program demonstrates pattern matching using fnmatch(), which applies glob-style matching:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <fnmatch.h>void list_matching_files(const char *pattern) {struct dirent *entry;DIR *dir = opendir(".");if (!dir) {perror("opendir");return;}while ((entry = readdir(dir)) != NULL) {if (fnmatch(pattern, entry->d_name, 0) == 0) {printf("%s\n", entry->d_name);}}closedir(dir);
}int main() {list_matching_files("*.c");  // Matches all `.c` files in the directoryreturn 0;
}

Example Output

If the directory contains main.c utils.c shell.c, running:

$ gcc globbing.c -o globbing
$ ./globbing
main.c
utils.c
shell.c

8. Conclusion

Globbing is a key feature of Shell parsing, allowing users to efficiently match filenames using wildcards. It differs from regular expressions and is processed before executing commands. Understanding globbing helps users write more efficient command-line operations and scripts. It is implemented at the Shell level using directory scanning and pattern matching algorithms.

Mastering globbing enables more effective batch file operations, automation, and scripting in Unix-based systems! 🚀

后记

2025年2月4日于山东日照。在GPT4o大模型辅助下完成。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/70113.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【物联网】ARM核常用指令(详解):数据传送、计算、位运算、比较、跳转、内存访问、CPSR/SPSR

文章目录 指令格式&#xff08;重点&#xff09;1. 立即数2. 寄存器位移 一、数据传送指令1. MOV指令2. MVN指令3. LDR指令 二、数据计算指令1. ADD指令1. SUB指令1. MUL指令 三、位运算指令1. AND指令2. ORR指令3. EOR指令4. BIC指令 四、比较指令五、跳转指令1. B/BL指令2. l…

Redis基础(二)——通用命令与五大基本数据类型

目录 一、Redis数据结构基本介绍 二、Redis通用命令 1.查看通用命令 2.KEYS&#xff1a;查看符合模板的所有key 3.DEL&#xff1a;删除指定的Key 4.lEXISTS&#xff1a;判断key是否存在 5.lEXPIRE&#xff1a;给一个key设置有效期&#xff0c;有效期到期时该key会被自…

ComfyUI工作流 参考图像生成人像手办(SDXL版)

文章目录 参考图像生成人像手办SD模型Node节点工作流程效果展示开发与应用参考图像生成人像手办 此工作流旨在实现将图像生成高精度的3D手办风格效果,通过深度学习技术完成从图像处理、模型加载、提示词优化到图像生成和超分辨率处理的一系列操作。整个流程以SDXL模型为核心,…

c语言 程序计算圆的面积(Program to find area of a circle)

给定圆的半径&#xff0c;求该圆的面积。 可以使用以下公式简单地计算圆的面积。 其中 r 是圆的半径&#xff0c;它可能是浮点数&#xff0c;因为饼图的值为 3.14 方法&#xff1a;使用给定的半径&#xff0c;使用上述公式找到面积&#xff1a;&#xff08;pi * r * r&#…

解析PHP文件路径相关常量

PHP文件路径相关常量包括以下几个常量&#xff1a; __FILE__&#xff1a;表示当前文件的绝对路径&#xff0c;包括文件名。 __DIR__&#xff1a;表示当前文件所在的目录的绝对路径&#xff0c;不包括文件名。 dirname(__FILE__)&#xff1a;等同于__DIR__&#xff0c;表示当前…

蓝桥杯C语言组:暴力破解

基于C语言的暴力破解方法详解 暴力破解是一种通过穷举所有可能的解来找到正确答案的算法思想。在C语言中&#xff0c;暴力破解通常用于解决那些问题规模较小、解的范围有限的问题。虽然暴力破解的效率通常较低&#xff0c;但它是一种简单直接的方法&#xff0c;适用于一些简单…

基于STM32的智能安防监控系统

1. 引言 随着物联网技术的普及&#xff0c;智能安防系统在家庭与工业场景中的应用日益广泛。本文设计了一款基于STM32的智能安防监控系统&#xff0c;集成人体感应、环境异常检测、图像识别与云端联动功能&#xff0c;支持实时报警、远程监控与数据回溯。该系统采用边缘计算与…

【Linux系统】CPU指令集 和 Linux系统权限 ring 0 / ring 3

CPU 指令集 CPU 指令集&#xff1a;是 CPU 实现软件指挥硬件执行的媒介&#xff0c;具体来说每一条汇编语句都对应了一条CPU指令&#xff0c;而非常非常多的 CPU 指令在一起&#xff0c;可以组成一个、甚至多个集合&#xff0c;指令的集合叫CPU指令集。 CPU 指令集有权限分级&…

Slint的学习

Slint是什么 Slint是一个跨平台的UI工具包&#xff0c;支持windows,linux,android,ios,web&#xff0c;可以用它来构建申明式UI,后端代码支持rust,c,python,nodejs等语言。 开源地址&#xff1a;https://github.com/slint-ui/slint 镜像地址&#xff1a;https://kkgithub.com/…

互联网行业常用12个数据分析指标和八大模型

本文目录 前言 一、互联网线上业务数据分析的12个指标 1. 用户数据&#xff08;4个&#xff09; (1) 存量&#xff08;DAU/MAU&#xff09; (2) 新增用户 (3) 健康程度&#xff08;留存率&#xff09; (4) 渠道来源 2. 用户行为数据&#xff08;4个&#xff09; (1) 次数/频率…

九. Redis 持久化-RDB(详细讲解说明,一个配置一个说明分析,步步讲解到位)

九. Redis 持久化-RDB(详细讲解说明&#xff0c;一个配置一个说明分析&#xff0c;步步讲解到位) 文章目录 九. Redis 持久化-RDB(详细讲解说明&#xff0c;一个配置一个说明分析&#xff0c;步步讲解到位)1. RDB 概述2. RDB 持久化执行流程3. RDB 的详细配置4. RDB 备份&恢…

[权限提升] Windows 提权 维持 — 系统错误配置提权 - Trusted Service Paths 提权

关注这个专栏的其他相关笔记&#xff1a;[内网安全] 内网渗透 - 学习手册-CSDN博客 0x01&#xff1a;Trusted Service Paths 提权原理 Windows 的服务通常都是以 System 权限运行的&#xff0c;所以系统在解析服务的可执行文件路径中的空格的时候也会以 System 权限进行解析&a…

通信易懂唠唠SOME/IP——SOME/IP-SD服务发现阶段和应答行为

一 SOME/IP-SD服务发现阶划分 服务发现应该包含3个阶段 1.1 Initial Wait Phase初始等待阶段 初始等待阶段的作用 初始等待阶段是服务发现过程中的一个阶段。在这个阶段&#xff0c;服务发现模块等待服务实例的相关条件满足&#xff0c;以便继续后续的发现和注册过程。 对…

【python】python基于机器学习与数据分析的手机特性关联与分类预测(源码+数据集)【独一无二】

&#x1f449;博__主&#x1f448;&#xff1a;米码收割机 &#x1f449;技__能&#x1f448;&#xff1a;C/Python语言 &#x1f449;专__注&#x1f448;&#xff1a;专注主流机器人、人工智能等相关领域的开发、测试技术。 python基于机器学习与数据分析的手机特性关联与分类…

测试csdn图片发布

测试csdn图片发布 ​​

JVM监控和管理工具

基础故障处理工具 jps jps(JVM Process Status Tool)&#xff1a;Java虚拟机进程状态工具 功能 1&#xff1a;列出正在运行的虚拟机进程 2&#xff1a;显示虚拟机执行主类(main()方法所在的类) 3&#xff1a;显示进程ID(PID&#xff0c;Process Identifier) 命令格式 jps […

51单片机 06 定时器

51 单片机的定时器属于单片机的内部资源&#xff0c;其电路的连接和运转均在单片机内部完成。 作用&#xff1a;1、用于计时&#xff1b;2、替代长时间的Delay&#xff0c;提高CPU 运行效率和处理速度。 定时器个数&#xff1a;3个&#xff08;T0、T1、T2&#xff09;&#xf…

洛谷 P1164 小A点菜 C语言

P1164 小A点菜 - 洛谷 | 计算机科学教育新生态 题目背景 uim 神犇拿到了 uoi 的 ra&#xff08;镭牌&#xff09;后&#xff0c;立刻拉着基友小 A 到了一家……餐馆&#xff0c;很低端的那种。 uim 指着墙上的价目表&#xff08;太低级了没有菜单&#xff09;&#xff0c;说&…

面向对象程序的三大特性之一的封装JAVA

1. 封装 1.1 封装的概念 面向对象程序三大特性&#xff1a;封装、继承、多态 。而类和对象阶段&#xff0c;主要研究的就是封装特性。何为封装呢&#xff1f;简单来说就是套壳屏蔽细节 。 比如&#xff1a;对于电脑这样一个复杂的设备&#xff0c;提供给用户的就只是&#…

[leetcode·回溯算法]回溯算法解题套路框架

本文参考labuladong算法笔记[回溯算法解题套路框架 | labuladong 的算法笔记] 本文解决几个问题&#xff1a; 回溯算法是什么&#xff1f;解决回溯算法相关的问题有什么技巧&#xff1f;如何学习回溯算法&#xff1f;回溯算法代码是否有规律可循&#xff1f; 其实回溯算法和我…