22.1 Checking programs existence

Array: mbfl_split_PATH

After a call to mbfl_program_split_path(): this array is filled with the components of the PATH variable.

Function: mbfl_program_split_path

If the number of pairs in the global array mbfl_split_PATH is zero: split the current value of PATH into its components by splitting the string using the colon character : as separator; store the result in the global array mbfl_split_PATH; finally return true.

If the number of pairs in the global array mbfl_split_PATH is not zero: do nothing and return false.

We can print the contents of the array with:

local -i i

for ((i=0; i < ${#mbfl_split_PATH[@]}; ++i))
do echo "${mbfl_split_PATH[$i]}"
done

To force a resplit, just reset the array to the empty state with:

mbfl_split_PATH=()
Function: mbfl_program_find PROGRAM
Function: mbfl_program_find_var _RV PROGRAM

Search for a file in the standard search path. Print the full pathname of the file found, or an empty string if nothing is found. When a file is found: return successfully; otherwise return by calling return_because_program_not_found().

PATH=/bin
local RESULT=$(mbfl_program_find ls)
"$RESULT"       ⇒ /bin/ls

The _var function variant will store the result in the variable _RV rather than print it.

PATH=/bin
mbfl_declare_varref(RESULT)
mbfl_program_find_var mbfl_datavar(RESULT) ls
"$RESULT"       ⇒ /bin/ls

These functions assume that: if a file is in the standard search path, it is meant to be an executable program. These functions do not actually test if the file is executable, they only test if the file exists; this is because we want to find files that are executable by another user, not just the effective user running the script.

The simpler way to test the availability of a program is to look for it just before it is used; the MBFL allows external programs to be run under a user different from the effective user running the script, so we delay the test for an executable file until the last moment, when the program will be actually run.

The search path is the one in the environment variable PATH as parsed by mbfl_program_split_path(). The contained directories are searched in the order in which they appear in PATH. There are rules:

  • If PROGRAM is an absolute pathname (according to mbfl_file_is_absolute()): only that absolute pathname is verified as existent file. PATH is ignored.
  • If PROGRAM is a relative pathname (a string with at least one slash character in it): only that relative pathname is verified as existent file. PATH is ignored.
  • If PROGRAM is a relative pathname without slash characters in it: the standard search path is used.

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