Why are heredoc redirections not allowed before a while loop

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Why are heredoc redirections not allowed before a while loop



The POSIX Shell Command Language allows redirections to follow compound commands. The standard says (emphasis mine)



The shell has several programming constructs that are "compound commands", which provide control flow for commands. Each of these compound commands has a reserved word or control operator at the beginning, and a corresponding terminator reserved word or operator at the end. In addition, each can be followed by redirections on the same line as the terminator. Each redirection shall apply to all the commands within the compound command that do not explicitly override that redirection.



For aesthetic reasons I want to put a heredoc before my while loop as in


<<'RECORDS' while
foo:bar
baz:quux
...
RECORDS
IFS=: read -r A B
do
# do something with A and B
done



because it makes the code easier to follow. However, it doesn't work in the shells I tried it (bash and dash). I get errors saying that the "while" command was not found and I assume that means that after the leading heredoc a simple command is expected and not a compound command.


bash


dash



I cannot move the heredoc to after read because then it reads the first line from a new heredoc on every iteration. I know that I can fix this by moving the heredoc to after done. I could also open a fd to a heredoc with exec before the loop and add a redirection to read.


read


done


exec


read



What's the reason redirections cannot occur before a compound command? Is there a shell that supports it since it's not explicitly prohibited by POSIX?









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Arduino Mega cannot recieve any sketches, stk500_recv() programmer is not responding

Visual Studio Code: How to configure includePath for better IntelliSense results

C++ virtual function: Base class function is called instead of derived