Question

I see this awk idiom all the time and I would like to know exactly what it means

while (getline <"FILE" > 0)

I understand what getline is doing, but I don't get redirection to 0.

According to The Awk Programming Language, you do this to avoid a infinite loop in the case of FILE being nonexistant.

Why does redirection get rid of that error? What exactly is being redirected? It can't be the return value of getline, otherwise, what expression is while evaluating? I'm missing something!

EDIT: Thanks for the comments. I got redirection operators confused with relational operators. Perhaps it would be clearer if it was written like this

while ((getline <"FILE") > 0)

Or even clearer

while (0 < (getline <"FILE"))
Was it helpful?

Solution

The > sign is testing the return value from getline (for greater than zero). It is not a redirection sign. From https://www.gnu.org/software/gawk/manual/html_node/Getline.html :

The getline command returns one if it finds a record and zero if it encounters the end of the file. If there is some error in getting a record, such as a file that cannot be opened, then getline returns -1. In this case, gawk sets the variable ERRNO to a string describing the error that occurred.

The confusion may come from the fact that output redirection to a file is not used by getline. (It is used only to read data). So there should be no ambiguity regarding the > sign. (It cannot mean output redirection) To print something to a file you can use output redirection from the print or printf commands.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top