M4

Before we look at how it's used with sendmail, let's have a brief look at m4 itself. We've just mentioned that it is a macroprocessor, but what exactly does that mean, and what does it do?

Given a text file as input, m4 will scan the file looking for predefined tokens it has been told about. If it finds any, it will perform a transformation on them, which will differ depending on what tasks we would like it to perform. Let's look at an example to show how this works in practice:

hydrogen# m4
define('eg', 'this is the first example')

eg
this is the first example
hydrogen#

First we can see that m4 reads standard input and writes to standard output. After starting the program, we've defined a macro that will substitute the string “eg” for the longer string “this is the first example.” Once the macro has been defined, we've entered the text to be scanned—“eg,” in this case. M4 realizes that this is a token it should work on and it has transformed it and generated the correct output.

The define command that we used is built into m4, along with many others such as ifdef, eval, ifelse, and len.

The following example expands on this by passing a file on to m4 that contains both the definitions and the input to be processed. We've also used the common convention of using a “.m4” extension for the file.

hydrogen# cat /tmp/test.m4
define('eg', 'this is example number ')

eg 1
eg 2
hydrogen# m4 /tmp/test.m4
this is example number 1
this is example number 2
hydrogen#

As a final example, let's create two files: one that contains the m4 definitions (we'll call this defs.m4), and a second that is the input file (we'll call this inputfile):

hydrogen# cat defs.m4
define('eg', 'this is example number ')
hydrogen#

hydrogen# cat inputfile
eg 1
eg 2
hydrogen#

We stated earlier that m4 writes to standard output, so let's run the program, passing the two files on the command line, and redirecting the standard output to a file at the same time—this will be our output file:

hydrogen# m4 defs.m4 inputfile > outputfile
hydrogen# cat outputfile
this is example number 1
this is example number 2
hydrogen#

This shows that outputfile now contains the correct processed text. Using this method has given us two main advantages over creating the file manually. It has allowed us to cut down the amount of text we need to enter in the input file, and it has automated the output file build procedure, which makes it less error-prone. Obviously these are very simple examples and so the advantages don't appear to be that great. But if we move on and examine m4's relationship with sendmail, the advantages should become clearer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset