manpagez: man pages & more
info gawk
Home | html | info | man

File: gawk.info,  Node: Nonfatal,  Next: Output Summary,  Prev: Close Files And Pipes,  Up: Printing

5.10 Enabling Nonfatal Output
=============================

This minor node 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.  For example:

     $ gawk '
     > BEGIN {
     >     PROCINFO["NONFATAL"] = 1
     >     ERRNO = 0
     >     print "hi" > "/no/such/file"
     >     if (ERRNO) {
     >         print("Output failed:", ERRNO) > "/dev/stderr"
     >         exit 1
     >     }
     > }'
     error-> Output failed: No such file or directory

   Here, 'gawk' did not produce a fatal error; instead it let the 'awk'
program code detect the problem and handle it.

   This mechanism works also for standard output and standard error.
For standard output, you may use 'PROCINFO["-", "NONFATAL"]' or
'PROCINFO["/dev/stdout", "NONFATAL"]'.  For standard error, use
'PROCINFO["/dev/stderr", "NONFATAL"]'.

   When attempting to open a TCP/IP socket (*note TCP/IP Networking::),
'gawk' tries multiple times.  The 'GAWK_SOCK_RETRIES' environment
variable (*note Other Environment Variables::) allows you to override
'gawk''s builtin default number of attempts.  However, once nonfatal I/O
is enabled for a given socket, 'gawk' only retries once, relying on
'awk'-level code to notice that there was a problem.

© manpagez.com 2000-2025
Individual documents may contain additional copyright information.