Reading command parameters from file with grep and awk

I was facing the problem today that I wanted to read the command line arguments for a program from a configuration file. I did also need to check the return value of the command executed.

Consider you have the following configuration file :

monte@raspberrypi ~ $ cat toolconfig
parameter,1,"FIRST",0x100
parameter,2,"SECOND",0x200
parameter,3,"THIRD",0x300

data,x,y
data,a,b

You could then use grep to extract all lines that start with „parameter“

monte@raspberrypi ~ $ grep ^parameter toolconfig
parameter,1,"FIRST",0x100
parameter,2,"SECOND",0x200
parameter,3,"THIRD",0x300

If you pipe the output of grep to awk and tell awk to split the lines by the comma you are half way there.

monte@raspberrypi ~ $ grep ^parameter toolconfig | awk -F',' '{ print " "$1 " " $2 " " $3 " " $4 }'
parameter 1 "FIRST" 0x100
parameter 2 "SECOND" 0x200
parameter 3 "THIRD" 0x300

The next step is to format the call that needs to be executed. In this example we simple execute the echo command. Since the first entry „parameter“ is only for identification we skip it with the next call. For now we do not execute anything but do only display the command.

monte@raspberrypi ~ $ grep ^parameter toolconfig | awk -F',' '{ print "echo -a " $2 " -b " $3 " -c " $4 }'
echo -a 1 -b "FIRST" -c 0x100
echo -a 2 -b "SECOND" -c 0x200
echo -a 3 -b "THIRD" -c 0x300

Many implementations of awk support the system command to execute other commands. The following line will execute the echo command with the options specified in the config file.

monte@raspberrypi ~ $ grep ^parameter toolconfig | awk -F',' '{ system( "echo -a " $2 " -b " $3 " -c " $4 ) }'
-a 1 -b FIRST -c 0x100
-a 2 -b SECOND -c 0x200
-a 3 -b THIRD -c 0x300

Awk works on a line by line basis. This means that the command surrounded by {} is executed for each line in our file (or each line provided by grep here). If we call a complex program with system it might report an error and we need to stop processing the other entries. This can be done by checking the return value of system.

monte@raspberrypi ~ $ grep ^parameter toolconfig | awk -F',' '{ if( system( "echo -a " $2 " -b " $3 " -c " $4 ) != 0 ) exit 1 }'
-a 1 -b FIRST -c 0x100
-a 2 -b SECOND -c 0x200
-a 3 -b THIRD -c 0x300
monte@raspberrypi ~ $ echo $?
0

If the echo command would fail for any of the lines the processing of the left over lines would stop. The return value which can be obtained with $? would be not equal to zero.

Happy scripting.