How do I get the exit status of a command in a getline pipeline?

Not an ideal solution, but you can do:

"command || echo failure" | getline var; ... if( var == "failure" ) exit;

There is some ambiguity in that you have to select the string "failure" in such a way that command can never generate the same string, but perhaps this is an adequate workaround.


The simplest thing to do is just echo the exit status from shell after the command executes and then read that with getline. e.g.

$ cat tst.awk    
BEGIN {
    cmd = "echo foo; echo bar; echo baz; false"

    mod = cmd "; echo \"$?\""
    while ((mod | getline line) > 0) {
        if (numLines++)
            print "got a line of text: " prev
        prev = line
    }
    status = line
    close(mod)

    if (status != 0) {
        print "ERROR: command '" cmd "' failed" | "cat >&2"
        exit 1
    }
    print "command '" cmd "' was successful"
}

$ awk -f tst.awk
got a line of text: foo
got a line of text: bar
got a line of text: baz
ERROR: command 'echo foo; echo bar; echo baz; false' failed
$ echo $?
1

In case anyone's reading this and considering using getline, make sure you read http://awk.freeshell.org/AllAboutGetline and FULLY understand all the caveats and implications of doing so first.

Tags:

Awk

Posix

Getline