对于gawk 4.2版本,答案在这里:
https://www.gnu.org/software/gawk/manual/html_node/Nonfatal.html。但是,在早期版本中似乎没有PROCINFO ["NONFATAL"]。
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
使用下面的awk程序:
$ cat nonFatal.awk
BEGIN {
PROCINFO["NONFATAL"] = 1
ERRNO = 0
print "hi" > "/no/such/file"
if (ERRNO) {
print("Output failed:", ERRNO) > "/dev/stderr"
exit 1
}
}
在gawk 4.0和4.1版本中,该错误仍然是致命的。
$ gawk -f nonFatal.awk
gawk: nonFatal.awk:4: fatal: can't redirect to `/no/such/file' (No such file or directory)
但在 gawk 4.2.1 中,它可以工作(我已经编译了 gawk 4.2.1 作为 gawk-4.2.1):
$ ./gawk-4.2.1 -f /var/tmp/nonFatal.awk
Output failed: No such file or directory