getopts 处理 shell 参数

💡 原文中文,约900字,阅读约需3分钟。
📝

内容提要

在 C 和 C++ 中处理命令行参数的方法包括 C 的 getopt 和 C++ 的 Boost Options 库。Shell 中使用 getopts(Bash 内置)和 getopt(独立可执行文件)。getopts 处理短选项简单,支持参数传递,适合大多数脚本需求。

🎯

关键要点

  • 处理命令行参数在 C 和 C++ 中使用 getopt 和 Boost Options 库。
  • Shell 中使用 getopts(Bash 内置)和独立的 getopt。
  • getopts 处理短选项简单,支持参数传递,适合大多数脚本需求。
  • 短选项示例:./test.sh -a -b -c 和 ./test.sh -abc。
  • 短选项示例:./test.sh -a args -b -c,其中 -a 需要参数。
  • 长选项示例:./test.sh --a-long=args --b-long。
  • 使用 getopts 的基本示例代码展示了如何处理选项和参数。
  • 绝大多数脚本可以使用 getopts,若需支持长选项和可选参数则需使用 getopt。

延伸问答

getopts 和 getopt 有什么区别?

getopts 是 Bash 内置的,而 getopt 是独立的可执行文件。

如何在 shell 脚本中使用 getopts?

可以通过 while 循环和 getopts 命令来处理选项和参数。

getopts 支持哪些类型的选项?

getopts 支持短选项和长选项,但主要用于短选项。

短选项和长选项的示例是什么?

短选项示例:./test.sh -a -b -c;长选项示例:./test.sh --a-long=args --b-long。

getopts 适合用于哪些场景?

getopts 适合大多数脚本需求,尤其是处理短选项时。

如果需要支持长选项,应该使用什么?

如果需要支持长选项和可选参数,则应使用 getopt。

➡️

继续阅读