用 getopts 解析命令行参数

用可移植的 shell 循环处理短选项和选项参数。

macOSBash 脚本自动化Shell脚本低风险
使用 while getopts "vn:" opt,把 -v 和 -n <值> 读入变量。

01命令

命令
$ while getopts "vn:" opt; do case $opt in v) verbose=1;; n) name=$OPTARG;; esac; done

02作用说明

getopts 在 shell 内实现标准 Unix 选项语法,包括合并短选项和必填参数,让脚本像系统工具一样接受参数。手写参数解析容易出错,图形界面无法提供这种接口约定。

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)
!注意: getopts 只处理短选项;--verbose 这类长选项需手写解析或使用 util-linux 的 getopt。

04撤销

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

05来源

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