gpt4 book ai didi

bash - 替代 for 循环构造

转载 作者:行者123 更新时间:2023-12-03 07:31:53 29 4
gpt4 key购买 nike

一般评论:任何对这个问题提供新的有用见解的新答案都将获得奖励。

Bash reference manual提到 Bash 支持
以下 for 循环结构:

for name [ [in [words ...] ] ; ] do commands; done
for (( expr1 ; expr2 ; expr3 )) ; do commands ; done
令人惊讶的是,以下 for 循环结构也是有效的:
for i in 1 2 3; { echo $i; }
for ((i=1;i<=3;++i)); { echo $i; }
这些不寻常的构造根本没有记录。 Bashmanual , Bash man-pages也不是 The Linux DocumentationProject提及这些结构。
调查时 language grammar可以看到使用
开闭大括号 ( { commands; } ) 作为 do commands; done 的替代品是为两者都实现的有效构造
for 循环和选择语句,可追溯到 Bash-1.14.7
[1]。
另外两个循环结构:
until test-commands; do consequent-commands; done
while test-commands; do consequent-commands; done
没有这种替代形式。

由于很多 shell 语言都是相关的,因此可以发现这些
结构也在那里定义并有详细记录。 KSH manual提到:

For historical reasons, open and close braces may be used instead of do and done e.g.

for i; { echo $i; } 

而 ZSH 实现和 documents其他循环结构的类似替代方案,但有局限性。它指出:

For the if, while and until commands, in both these cases thetest part of the loop must also be suitably delimited, such as by[[ ... ]] or (( ... )), else the end of the test will not be recognized.



问题:这个结构的起源是什么,为什么
这不会传播到其他循环结构?

更新 1:有一些很 usefuleducational下面的评论
这篇文章指出这是一个未记录的 Bourne Shell 功能,它似乎是早期 C-vs-sh 语言战斗的结果。

更新 2:在提出问题时:为什么没有记录此语言功能?到 Gnu Bash mailinglist ,我从 Chet Ramey(目前 GNU bash 的首席开发人员)那里收到了以下回答:

It's never been documented. The reason bash supports it (undocumented) isbecause it was an undocumented Bourne shell feature that we implementedfor compatibility. At the time, 30+ years ago, there were scripts that usedit. I hope those scripts have gone into the dustbin of history, but whoknows how many are using this construct now.

I'm going to leave it undocumented; people should not be using it anyway.



相关问答:
  • A bash loop with braces?
  • Hidden features of Bash ( this answer )
  • [U&L] What is the purpose of the “do” keyword in Bash for loops?

  • 脚注: [1] 我没有找到更早的版本,我相信它早于这个

    最佳答案

    [W]hy is this not propagated to the other loop-constructs?


    的支撑形式而 直到 命令在语法上会很模糊,因为你不能分开 测试命令 来自 后续命令 它们之间没有明显的分隔符,因为它们都是 defined by POSIX成为 化合物lists .
    例如,支持此类构造的 shell 可以选择以下命令中的任一大括号组作为 后续命令 无论哪种方式,这都是一个合理的选择。
    while true; { false; }; { break; }
    由于其形式不明确,该命令可以转换为以下任一形式;两者都没有比另一个更准确的翻译,它们做的事情完全不同。
    while true; do
    false
    done
    break
    while true; { false; }; do
    break
    done
    command 不受这种歧义的影响,因为它的第一部分 - 一个变量名,可选后跟 和单词列表,或 (( 的特殊形式复合命令——可以很容易地与形成其第二部分的花括号组区分开来。
    鉴于我们已经对 有了一致的语法。而 直到 命令,我真的认为向他们传播这种替代形式没有任何意义。
    Wrt它的起源,见:
  • Characteristical common properties of the traditional Bourne shells ,
  • Stephen Bourne's talk at BSDCon ,
  • Unix v7 source code, sh/cmd.c .
  • 关于bash - 替代 for 循环构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63247449/

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