gpt4 book ai didi

shell - 是否有最低限度的 POSIX.2 兼容 shell ?

转载 作者:行者123 更新时间:2023-12-03 12:38:15 24 4
gpt4 key购买 nike

是否有最低限度的POSIX .2 兼容的 shell (我们称之为 mpcsh)在以下意义上:
如果 mpcsh myscript.sh在我的(兼容)系统上正确运行然后 xsh myscript.sh对于任何符合 POSIX.2 的 shell xsh 的行为都相同在任何兼容的系统上。 (“相同”直到不太相关的事情,如错误消息的措辞等)
是否dash合格吗?
如果不是,有什么方法可以验证myscript.sh的合规性吗? ?

编辑(9年后):
接受的答案仍然有效,但请查看 this blog postchackbashisms命令( source )。避免 bashisms 与编写符合 POSIX.2 的 shell 脚本不同,但它很接近。

最佳答案

悲伤的回答提前

它不会帮助你(不像你期望的那样可靠和可靠)。

这是为什么。

虚拟“POSIX shell”无法解决的一个大问题是措辞含糊或标准中没有解决的问题,因此 shell 可以在仍然遵守标准的同时以不同的方式实现事物。

以这两个关于管道的例子为例,第一个是众所周知的:

示例 1 - 范围界定

$ ksh -c 'printf "foo" | read s; echo "[${s}]"'
[foo]

$ bash -c 'printf "foo" | read s; echo "[${s}]"'
[]
ksh在当前 shell 中执行管道的最后一条命令,而 bash在子shell中执行所有——包括最后一个命令。 bash 4介绍了 lastpipe选项使它的行为类似于 ksh :
$ bash -c 'shopt -s lastpipe; printf "foo" | read s; echo "[${s}]"'
[foo]

所有这些都是(有争议的)根据 the standard :

Additionally, each command of a multi-command pipeline is in a subshell environment; as an extension, however, any or all commands in a pipeline may be executed in the current environment.



我不是 100% 确定它们对扩展的含义,但根据文档中的其他示例,这并不意味着 shell 必须提供一种在行为之间切换的方法,而只是说它可以(如果愿意的话)实现一些东西以这种“扩展方式”。其他人对此有不同的理解并争论 ksh行为不符合标准,我明白为什么。这种措辞不仅不吉利,而且一开始就允许这样做也不是一个好主意。

在实践中,哪种行为是正确的并不重要,因为它们是“两个大 shell ”“”,人们会认为如果你不使用他们的扩展并且只使用符合 POSIX 的代码,它就可以工作要么,但事实是,如果您依赖上面提到的一种或另一种行为,您的脚本可能会以可怕的方式中断。

示例 2 - 重定向

这是我几天前才知道的,见我的回答 here :
foo | bar 2>./qux | quux

常识和 POLA告诉我当下一行代码被命中时, quuxbar应该已经完成​​运行,这意味着文件 ./qux人满为患。对?不。

POSIX指出

If the pipeline is not in the background (see Asynchronous Lists), the shell shall wait for the last command specified in the pipeline to complete, and may also wait for all commands to complete.)



可以(!)等待所有命令完成!哇!

等待:

The shell waits for all commands in the pipeline to terminate before returning a value.



但是 没有:

Each command, except possibly the last, is run as a separate process; the shell waits for the last command to terminate.



因此,如果您在管道之间使用重定向,请确保您知道自己在做什么,因为这会受到不同的对待,并且可能会在边缘情况下严重中断,具体取决于您的代码。

我可以举另一个与管道无关的例子,但我希望这两个就足够了。

结论

有标准是好的,不断修改更好,坚持是好的。但是,如果标准由于模棱两可或宽容而失败,事情仍然可能出乎意料地破坏,实际上使标准的用处无效。

这在实践中意味着,除了编写“符合 POSIX 标准”的代码之外,您仍然需要思考并知道您正在做什么以防止某些事情发生。

话虽如此,但尚未提及的一个 shell 是 posh 这应该是 POSIX 加上比 dash 更少的扩展根据其联机帮助页具有,(主要是 echo -nlocal 关键字):

BUGS
Any bugs in posh should be reported via the Debian BTS.
Legitimate bugs are inconsistencies between manpage and behavior,
and inconsistencies between behavior and Debian policy
(currently SUSv3 compliance with the following exceptions:
echo -n, binary -a and -o to test, local scoping).

天啊。

关于shell - 是否有最低限度的 POSIX.2 兼容 shell ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11376975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com