Does the loop processing in bash work even if it is enclosed in parentheses?

Asked 1 years ago, Updated 1 years ago, 85 views

I think the loop processing in Bash will be sandwiched between do and don as shown below.

#!/bin/bash
for fin./*
do
    echo$f
done

As a trial, {} also worked as intended.

#!/bin/bash

for fin./*
{
    echo$f
}

execution results:

$./scripts2.sh 
./ scripts.sh
./ scripts2.sh

I didn't understand the reason why it worked even if I surrounded it with {}, but could you tell me why this code works?

bash

2022-09-30 19:30

1 Answers

I didn't know how it was implemented, but as far as the Bash implementation goes, this syntax was allowed only for https://git.savannah.gnu.org/cgit/bash.git/tree/parse.y?id=9439ce094c9aa7557a9d53ac7b412a23aa66e36b#n805

 for_command: FOR WORD newline_list DO compound_list DONE
            {
              $$ = make_for_command($2, add_string_to_list("\"$@\"",(WORD_LIST*)NULL), $5, word_lineno[word_top]);
              if(word_top>0)word_top--;
            }
    |   FOR WORD newline_list '{'compound_list'}'
            {
              $$ = make_for_command($2, add_string_to_list("\"$@\"",(WORD_LIST*)NULL), $5, word_lineno[word_top]);
              if(word_top>0)word_top--;
            }
(Omitted hereinafter)

As far as I know, this syntax is not documented.For example, in the Bash documentation, https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Looping-Constructs describes for, but only the syntax in do...don format is written.

The English version of Stack Overflow also had a question about this syntax, and no documentation was found in the answer that existed when writing this answer: https://stackoverflow.com/q/22619510/5989200


2022-09-30 19:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.