用 case 按模式分派

在脚本中匹配通配模式并执行对应分支。

macOSBash 脚本Shell脚本低风险
使用 case "$arg" in *.tar.gz) ...;; *.md) ...;; esac,按模式分派。

01命令

命令
$ case "$1" in *.tar.gz) echo archive;; *.md) echo docs;; *) echo other;; esac

02作用说明

case 直接支持 *.tar.gz 等通配模式,使按扩展名或参数分派简短可读,无需正则库,是 CLI 工具的标准 shell 结构。

03风险

风险低风险
使用条件macOS default zsh/bash (bash 3.2+; some features need bash 4+ via Homebrew)
系统兼容性macOS with bash 3.2+ (GNU bash 4+ via Homebrew for advanced features)
!注意: 模式是通配而非正则;. 无需转义,但正则量词无效。

04撤销

✓无需撤销——该命令不会改变持久状态。

05来源

最后验证: 2026-10-13 · 分类: 开发者