BEGIN

Begin Blocks

The awk programming language allows us to use begin blocks and end blocks to provide [[startup?]] and [[cleanup?]] actions within the program.

Execution

Begin blocks act as [[constructor?]]s and are executed once only before the first input record is read. Begin blocks are prefixed with the BEGIN keyword and each block is contained in squiggly brace enclosures. There is no default action provided for begin block, so they must contain explicit actions. Begin blocks are typically used to initialize variables, such as the record separator and field separator, but they can contain other commands:

BEGIN {
  # This is a begin block
  print "The awk parser" # Print the title
  # Set the field separator to a colon
  FS = ":"
}

Behaviour and effects

Begin blocks are executed before the first input record is read, so there is no current record when a begin block is run. If multiple begin blocks are defined within a script, they are executed in order that they are defined within the awk script.

If the script contains only BEGIN rules and no other rules, then the script exits without reading the input, after the BEGIN rules have been run. However, if an END rule exists, then the input is read, even if there are no other rules in the program. This behaviour is portable across all nawk implementations and exists because the END rule may need to check the FNR and NR variables. Older versions of awk may read the input even if the script has just a BEGIN rules.

Programming Convention

The original version of awk required the begin block to be placed at the beginning of the program and only one begin block was allowed. This is no longer a requirement of current awk versions, however it is recommended that this convention is observed for portability and readability purposes.

Multiple Begin Blocks

When multiple begin blocks are defined within a script, they are executed in order that they are defined.

Special Variables

FILENAME

Normally the FILENAME variable is not populated within a BEGIN section. However, a non redirected call to getline will cause FILENAME to become set.