Shell 脚本 getopts 选项

2025 年 3 月 17 日 | 阅读 1 分钟

getopts 选项用于 shell 脚本中,以解析传递给它们的参数。 当在命令行上传递参数时,getopts 会解析这些参数,而不是命令行。

选项以连字符 (-) 开头,后跟字母。 例如,-a, -b, -c, -d 等。

示例 1 无参数

Linux Shell Scripting Get script options with getopts 1

看看上面的快照,我们创建了三个选项 -a、-b 和 -c。 并且任何选项都不需要参数。

Linux Shell Scripting Get script options with getopts 2

看看上面的快照,这是上面脚本的示例输出。

示例 2 带参数

Linux Shell Scripting Get script options with getopts 3

看看上面的快照,选项 b 需要参数。

Linux Shell Scripting Get script options with getopts 4

看看上面的快照,这是上面脚本的示例输出。

下一个主题if then else