If I have a colon-separated path list, much like $PATH, but not neccessarily $PATH.
I want to search that list for a specific file name. However, I only want the first matching path.
I have considered the following linux commands:
which
: only works for binary, and only works with $PATH variablewhereis
: works with particular kinds of files, and only works with $PATH variablefind
: does not support colon-separated path lists, and returns multiple results
Here are some things I have tried:
I have tried to use
whereis
by the following strategyenv WHEREIS="`which whereis`" PATH="$MY_PATH_LIST" $WHEREIS "$TARGET_FILE"
and this almost works. However, it does not seem to return results for arbitrary file types. It also returns multiple results, and in an awkward format.
I could get
which
to work byenv WHICH="`which which`" PATH="$MY_PATH_LIST" $WHICH "$MY_TARGET_FILE"
if there was a command-line option to force it to allow non-executables.
I then tried to solve the problem with
find
. First I used regular expressions to expand the path list (I replace colons with spaces). Then I invoke find, and it works correctly. However, it searches all of the paths. I cannot seem to find a way to tell it to stop the search early if it finds a good result.I did get this to work
find ${MY_PATH_LIST//[:]/ } -name "$MY_TARGET_FILE" | head -n 1
but it takes a long time to complete, because
find
is still doing an exhaustive search.I need this to execute faster (exit on first result), because it would be run many times, with different parameters.
Does anyone have a better solution to suggest?
Note that if all fails, I can write a non-bash solution. Write now I'm hoping for a simple solution using existing tools.