Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Testing on the return codes of gawk's getline command.

14 views
Skip to first unread message

Hongyi Zhao

unread,
Oct 8, 2016, 9:45:35 PM10/8/16
to
Hi all,

The manual page of gawk said that:

The getline command returns 1 on success,
0 on end of file, and -1 on an error.

So I try to testing on the different return codes as following:

werner@debian-01:~$ echo 1 > aa
werner@debian-01:~$ awk 'BEGIN{while (( getline < "aa" ) == 0) print $0}'
werner@debian-01:~$ awk 'BEGIN{while (( getline < "aa" ) > 0) print $0}'
1
werner@debian-01:~$ awk 'BEGIN{while (( getline < "aa" ) >= 0) print $0}'
1
1
1
1
1
1
^C

The first case will give nothing, while the last case will be a dead-loop
for print the file's content over and over.

But I cann't figure out why gawk will work like this behavior according
to the return codes described in the manual page?

Regards
--
.: Hongyi Zhao [ hongyi.zhao AT gmail.com ] Free as in Freedom :.

Barry Margolin

unread,
Oct 8, 2016, 11:51:56 PM10/8/16
to
In article <ntc7fr$ber$1...@aspen.stu.neva.ru>,
Hongyi Zhao <hongy...@gmail.com> wrote:

> Hi all,
>
> The manual page of gawk said that:
>
> The getline command returns 1 on success,
> 0 on end of file, and -1 on an error.
>
> So I try to testing on the different return codes as following:
>
> werner@debian-01:~$ echo 1 > aa
> werner@debian-01:~$ awk 'BEGIN{while (( getline < "aa" ) == 0) print $0}'

The first call to getline returns 1. This is not == 0, so the loop ends
immediately.

> werner@debian-01:~$ awk 'BEGIN{while (( getline < "aa" ) > 0) print $0}'
> 1

The first call to getline returns 1. This is > 0, so the loop body
executes and prints the line. The second call returns 0, which is not >
0, so the loop ends.

> werner@debian-01:~$ awk 'BEGIN{while (( getline < "aa" ) >= 0) print $0}'
> 1
> 1
> 1
> 1
> 1
> 1
> ^C
>
> The first case will give nothing, while the last case will be a dead-loop
> for print the file's content over and over.

The first call to getline returns 1, which is >= 0, so the loop body is
executed. The next call returns 0, which is also >= 0, so the loop body
is executed again. But since it didn't actually read anything, $0 still
holds its previous value, so print $0 prints the first line. The next
call returns 0 again (since you're still at EOF), so this repeats over
and over.

This loop will only end when it gets an error, but that never happens.
It just stays at EOF.

>
> But I cann't figure out why gawk will work like this behavior according
> to the return codes described in the manual page?
>
> Regards

--
Barry Margolin, bar...@alum.mit.edu
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***

Ed Morton

unread,
Oct 9, 2016, 7:14:03 PM10/9/16
to
It's doing EXACTLY what the man page and the 2 line excerpt you provided says
it'll do. What did you think it would do?

Ed.
0 new messages