A bash loop with braces?

后端 未结 1 512
说谎
说谎 2021-01-17 23:02

I stumbled across this oddity and can\'t quite figure out why it works:

$ for ((i=0;i<8;i++)) {
>   printf \'%d...\' \"$i\";
> }; echo
0...1...2...3         


        
相关标签:
1条回答
  • 2021-01-17 23:29

    Transferring some comments into an answer:

    AFAIK, it is a largely undocumented hack in Bash, probably needed for compatibility with the Bourne shell which also supported the brace notation, also undocumented. It is not peculiar to Mac OS X; it works like that on Ubuntu 12.04 too. It doesn't seem to work with while loops or until loops in Bash, though.

    How do you write an arithmetic for loop in Bourne shell syntax?

    It is an optional way of writing the body of the for loop; the condition would be written differently in Bourne shell, but you could write things like

    for i in 1 2 3
    {
        echo $i
    }
    

    in Bourne shell, or use do in place of { and done in place of }.

    (I'd forgotten that it existed until your question reminded me of it; I've never used it seriously because it was not documented and hence not guaranteed to be supported.)

    The do ... done construct cannot be used where { ... } can be used; you can only use do ... done after a for, while or until loop, whereas you can write { echo Hi; } anywhere a command could appear (e.g. if { echo Hi; }; then echo Lo; fi. You can't do that with do and done.

    The best way to check the veracity of this answer is likely to be to download the Heirloom Bourne Shell from the Heirloom Project.


    I've downloaded the source code for the Heirloom Bourne Shell (a CVS repository) and built it, and tested it. It does indeed accept the braces after the for loop, and refuses to recognize them as surrogates for do and done after an until or while loop.

    0 讨论(0)
提交回复
热议问题