Monday, June 19, 2017

PATH building

Throughout UNIX configuration activities is not uncommon to have to set up environment variables for a variety of reasons, most notably for several variants of PATH searches, such as PATH, LD_LIBRARY_PATH, PKG_CONFIG_PATH and many others. In order to generalize and simplify the process it's not also uncommon to take advantage of shell scripts and in doing so the process can also be made more flexible and dynamic in terms of building these PATHs by testing for a particular system support condition.

NOTE
In building PATHs that support multiple components, between every two components there's a certain delimiter character which may vary according to different usage conventions. Sometimes the delimiter may be a ':', other times it may be a ';', but it's not necessarily restricted to these two.
For instance, let's say that on a developer system one needs to set PKG_CONFIG_PATH according to some previously known "packages" (for instance, libffi and sqlite), but constrained to the availability of these "packages" on that particular system. The essential idea of a shell script excerpt to address this scenario could be:

PKG=/opt/libffi-3.2/gnu32
if [[ -d "$PKG" ]] ; 

then

  CFG=$PKG/lib/pkgconfig
  PCP=${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}
  ! [[ "$PCP" =~ "$PKG" ]] && \
    export PKG_CONFIG_PATH=$CFG$PCP


fi

PKG=/opt/sqlite-3.19.3/gnu32
if [[ -d "$PKG" ]] ; 

then

  CFG=$PKG/bin
  ! [[ "$PATH" =~
"$PKG" ]] && \
    export PATH=$CFG:$PATH

  CFG=$PKG/lib/pkgconfig
  PCP=${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}
  ! [[ "$PCP" =~ "$PKG" ]] && \
    export PKG_CONFIG_PATH=$CFG$PCP


fi


In the above code, note the following points:
  
  • I'm assuming BASH as it may have been readily apparent.
      
  • I test beforehand for the existence of each "package" directory.
    ( if [[ -d ... ]] ; )
      
  • I test if the path component has already been previously set.
    ( ! [[ "$PKG_CONFIG_PATH" =~ ... ]] && ... )
      
  • If PKG_CONFIG_PATH isn't set or is empty, don't add the delimiter ':'.
    I could have done this each time to avoid future copy/paste "bugs".
    ( ${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH} )

NOTE
By the way, the above "packages" are just two out of a bunch more prerequisites to build a more recent Firefox version under a Solaris 11.3 GA / Release :-D
NOTE
In particular, the kind of the above script is typically not executable and is intended to be run as an argument to the source command in order to integrate the settings to an existing session. As such, on this kind of script, case needed, use return instead of exit.
A slightly more elaborated and fully woking example of this technique can be found on another post I've written about GNU - Build preparation.