awk - test if print was successful

Viewed 294

There are a few reasons why a print statement in awk may not succeed: no permissions to write to the specified file, file doesn't exist and awk can't create it, etc. How is it possible to test the success of an awk print statement? I've tried the following:

$ cat printError.awk
BEGIN {
    if (! (print("Hello") > "/this/doesnt/exist")) {
        print "Could not print"
    }
}

But it gives a syntax error, I think because print is a statement and not a function.

$ awk -f printError.awk 
awk: printError.awk:2:  if (! (print("Hello") > "/this/doesnt/exist")) {
awk: printError.awk:2:         ^ syntax error
awk: printError.awk:2:  if (! (print("Hello") > "/this/doesnt/exist")) {
awk: printError.awk:2:                                               ^ syntax error
awk: printError.awk:2:  if (! (print("Hello") > "/this/doesnt/exist")) {
awk: printError.awk:2:                                                 ^ syntax error

EDIT: I found a solution for gawk 4.2+, but the environment I'm working in has only 4.0, so I'm still looking for a solution for that version.

1 Answers

For gawk 4.2, the answer is here: https://www.gnu.org/software/gawk/manual/html_node/Nonfatal.html. But it seems that PROCINFO["NONFATAL"] is not present in earlier versions.

5.10 Enabling Nonfatal Output

This section describes a gawk-specific feature.

In standard awk, output with print or printf to a nonexistent file, or some other I/O error (such as filling up the disk) is a fatal error.

$ gawk 'BEGIN { print "hi" > "/no/such/file" }' error→ gawk: cmd. line:1: fatal: can't redirect to `/no/such/file' (No error→ such file or directory)

gawk makes it possible to detect that an error has occurred, allowing you to possibly recover from the error, or at least print an error message of your choosing before exiting. You can do this in one of two ways:

For all output files, by assigning any value to PROCINFO["NONFATAL"].
On a per-file basis, by assigning any value to PROCINFO[filename, "NONFATAL"]. Here, filename is the name of the file to which you wish

output to be nonfatal.

Once you have enabled nonfatal output, you must check ERRNO after every relevant print or printf statement to see if something went wrong. It is also a good idea to initialize ERRNO to zero before attempting the output

Using the following awk program:

$ cat nonFatal.awk 
BEGIN {
    PROCINFO["NONFATAL"] = 1
    ERRNO = 0
    print "hi" > "/no/such/file"
    if (ERRNO) {
        print("Output failed:", ERRNO) > "/dev/stderr"
        exit 1
    }
}

the error is still fatal in gawk 4.0 and 4.1

$ gawk -f nonFatal.awk 
gawk: nonFatal.awk:4: fatal: can't redirect to `/no/such/file' (No such file or directory)

But in gawk 4.2.1 it works (I had compiled gawk 4.2.1 as gawk-4.2.1):

$ ./gawk-4.2.1 -f /var/tmp/nonFatal.awk 
Output failed: No such file or directory
Related