Previous: Location, Up: Miscellaneous


13.3 Exiting from m4

If you need to exit from m4 before the entire input has been read, you can use m4exit:

— Builtin: m4exit ([code = `0'])

Causes m4 to exit, with exit status code. If code is left out, the exit status is zero. If code cannot be parsed, or is outside the range of 0 to 255, the exit status is one. No further input is read, and all wrapped and diverted text is discarded.

A common use of this is to abort processing:

— Composite: fatal_error (message)

Abort processing with an error message and non-zero status. Prefix message with details about where the error occurred, and print the resulting string to standard error.

     define(`fatal_error',
            `errprint(__program__:__file__:__line__`: fatal error: $*
     ')m4exit(`1')')
     =>
     fatal_error(`this is a BAD one, buster')
     error-->m4:stdin:4: fatal error: this is a BAD one, buster

After this macro call, m4 will exit with exit status 1. This macro is only intended for error exits, since the normal exit procedures are not followed, e.g., diverted text is not undiverted, and saved text (see M4wrap) is not reread. (This macro has a subtle bug, when invoked from wrapped text. You should try to see if you can find it and correct it. see Answers)

     m4wrap(`This text is lost to `m4exit'.')
     =>
     divert(`1') And so is this.
     divert
     =>
     m4exit

Note that it is still possible for the exit status to be different than what was requested by m4exit. If m4 detects some other error, such as a write error on standard out, the exit status will be non-zero even if m4exit requested zero.

If standard input is seekable, then the file will be positioned at the next unread character. If it is a pipe or other non-seekable file, then there are no guarantees how much data m4 might have read into buffers, and thus discarded.