Inlining path_exists

The path_exists function in eutils was meant as a simple hack to check for existence of files matching a wildcard. However, it was kinda ugly and never became used widely. At this very moment, it is used correctly in three packages, semi-correctly in one package and totally misused in two packages. Therefore, I think it’s time to replace it with something nicer.

The replacement snippet is rather trivial (from the original consumer, eselect-opengl):

local shopt_saved=$(shopt -p nullglob)
shopt -s nullglob
local opengl_dirs=( "${EROOT%/}"/usr/lib*/opengl )
${shopt_saved}

if [[ -n ${opengl_dirs[@]} ]]; then
	# ...
fi

Through using nullglob, you disable the old POSIX default of leaving the wildcard unexpanded when it does not match anything. Instead, you either simply get an empty array or a list of matched files/directories. If your code requires at least one match, you check for the array being empty; if it handles empty argument lists just fine (e.g. for loops), you can avoid any conditionals. As a side effect, you get the expanded match in an array, so you don’t have to repeat the wildcard multiple times.

Also note using shopt directly instead of estack.eclass that is broken and does not restore options correctly. You can read more on option handling in Mangling shell options in ebuilds.

Update: one-liner from Ulrich Müller

if ( shopt -s failglob; : /foo/bar/baz* ) 2>/dev/null; then
    # ...
fi

2 thoughts on “Inlining path_exists”

  1. This is sort of complicated. The following will achieve the same, without the need for extra variables:


    if ( shopt -s failglob; : /foo/bar/baz* ) 2>/dev/null; then
    # ...
    fi

Leave a Reply

Your email address will not be published.