22.3.9 Defining program–execution functions

It happens often that we want to execute an external program; it is useful to wrap into a function the machinery needed to use program declaration and execution with MBFL’s facilities. Some preprocessor macros automate this function definition.

Let’s say we want to define a function to execute pamixer, PulseAudio’s mixer program; we can use the macro MBFL_DEFINE_PROGRAM_EXECUTOR():

mbfl_declare_program pamixer

MBFL_DEFINE_PROGRAM_EXECUTOR([[[pamixer]]], [[[pamixer]]])

the macro use will expand into:

function program_pamixer () {
    mbfl_declare_varref(PROGRAM)
    mbfl_program_found_var mbfl_datavar(PROGRAM) pamixer || exit $?
    mbfl_program_exec "$PROGRAM"  "$@"
}

we can use the function as:

if ! program_pamixer --increase 2
then
    # handle the error
fi

the function will return with status equal to the exit status of the program.

Preprocessor Macro: MBFL_DEFINE_PROGRAM_EXECUTOR (STEM, EXECUTABLE_PATHNAME, OPTIONAL_DEFAULT_FLAGS, OPTIONAL_FUNCTION_PREFIX)

Define a function we can call to execute an external program previously declared with mbfl_declare_program() and similar functions; Declaring the intention to use a program. The program is executed with mbfl_program_exec(); Core API for Program execution.

STEM

A string used to compose the function name, which will be: program_STEM.

EXECUTABLE_PATHNAME

The executable specification of the program; it must be the same string used as argument to mbfl_declare_program().

OPTIONAL_DEFAULT_FLAGS

Optional sequence of strings that will be inserted on the command line of the program.

OPTIONAL_FUNCTION_PREFIX

Optional function–name prefix.

With this preprocessor version the expansion of a macro use looks like this:

function OPTIONAL_FUNCTION_PREFIXprogram_STEM () {
    mbfl_declare_varref(PROGRAM)
    mbfl_program_found_var mbfl_datavar(PROGRAM) EXECUTABLE_PATHNAME || exit $?
    mbfl_program_exec "$PROGRAM" OPTIONAL_DEFAULT_FLAGS "$@"
}
Preprocessor Macro: MBFL_DEFINE_PROGRAM_REPLACER (STEM, EXECUTABLE_PATHNAME, OPTIONAL_DEFAULT_FLAGS, OPTIONAL_FUNCTION_PREFIX)

Like MBFL_DEFINE_PROGRAM_REPLACER(), but uses mbfl_program_replace() rather than mbfl_program_exec(); Core API for program execution with replacement.

If the optional parameter OPTIONAL_FUNCTION_PREFIX is not used: the generated function name is:

program_replace_STEM

otherwise it is:

OPTIONAL_FUNCTION_PREFIXprogram_replace_STEM

This document describes version 3.0.0-devel.9 of Marcos Bash Functions Library.