哪个是更标准的包,getopt 或 getopts(带有“s”)?

aba*_*ter 7 linux posix getopts

标准实用程序的 Linux 基础列表包括getopts但不包括getopt. Posix 实用程序的Open Group列表类似。

同时,维基百科的标准 Unix 命令列表包括getopt但不包括getopts. 同样,Windows Subsystem for Linux(基于 Ubuntu 基于 Debian)也包括getopt但不包括getopts(它是GNU 增强版)。

balter@spectre:~$ which getopt
/usr/bin/getopt
balter@spectre:~$ getopt -V
getopt from util-linux 2.27.1
balter@spectre:~$ which getopts
balter@spectre:~$ 
Run Code Online (Sandbox Code Playgroud)

因此,如果我想选择一个我最有信心使用更标准 Linux 发行版(例如 Debian、Red Hat、Ubuntu、Fedora、CentOS 等)的人,我应该选择哪个?

笔记:

感谢 Michael 和 Muru 解释了内置与可执行文件。我刚刚也偶然发现了这个,其中列出了 bash 内置函数。

mur*_*uru 15

which是错误的工具。getopts通常也是一个内置

由于getopts影响当前的shell执行环境,所以一般作为shell常规内置提供。

~ for sh in dash ksh bash zsh; do "$sh" -c 'printf "%s in %s\n" "$(type getopts)" "$0"'; done
getopts is a shell builtin in dash
getopts is a shell builtin in ksh
getopts is a shell builtin in bash
getopts is a shell builtin in zsh
Run Code Online (Sandbox Code Playgroud)

如果您使用的是 shell 脚本,则可以安全地依赖getopts. 可能有其他原因偏爱其中一个,但这getopts标准的

另请参阅:为什么不使用“which”?那用什么?

  • 不久前,“getopt”被删除,取而代之的是“getopts”。然而,新的 GNU 增强的 `getopt` 似乎比 `getopts` 有所改进。但如果 `getopts` 是 Posix 标准,那么我应该暂时坚持它。 (2认同)

小智 5

我也更愿意getopts这样做getopt,原因如下:

getopt缺点

  1. 外部实用程序
  2. 无法处理传统版本中的空参数字符串或嵌入空格的参数

getopts优点

  1. 可在任何 POSIX shell 中工作并且是可移植的
  2. -a -b与 以及配合良好-ab