The system( ) Function

The system( ) function executes a command supplied as an expression.[3] It does not, however, make the output of the command available within the program for processing. It returns the exit status of the command that was executed. The script waits for the command to finish before continuing execution. The following example executes the mkdir command:

BEGIN { if (system("mkdir dale") != 0) 
		print "Command Failed" }

The system( ) function is called from an if statement that tests for a non-zero exit status. Running the program twice produces one success and one failure:

$ awk -f system.awk
$ ls dale
$ awk -f system.awk
mkdir: dale: File exists
Command Failed

The first run creates the new directory and system( ) returns an exit status of 0 (success). The second time the command is executed, the directory already exists, so mkdir fails and produces an error message. The “Command Failed” message is produced by awk.

The Berkeley UNIX command set has a small but useful command for troff users named soelim, named because it “eliminates” “.so” lines from a troff input file. (.so is a request to include or “source” the contents of the named file.) If you have an older System V system that does not have soelim, you can use the following awk script to create it:

/^\.so/ { gsub(/"/, "", $2)
		system("cat " $2)
		next
		}
{ print }

This script looks for “.so” at the beginning of a line, removes any quotation marks, and then uses system( ) to execute the cat command and output the ...

Get sed & awk, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.