Finding a File Using a List of Possible Locations
Problem
You need to execute, source, or read a file, but it may be located in a number of
different places in or outside of the $PATH
.
Solution
If you are going to source the file and it’s located somewhere on
the $PATH
, just source
it. bash’s built-in source
command (also known by the shorter-to-type but harder-to-read
POSIX name “.”) will search the $PATH
if the sourcepath
shell option is
set, which it is by default:
$ source myfile
If you want to execute a file only if you know it exists in the
$PATH
and is executable, and you have
bash version 2.05b or higher, use type -P
to search the $PATH. Unlike the which
command, type -P
only produces output
when it finds the file, which makes it much easier to use in this
case:
LS=$(type -P ls) [ -x $LS ] && $LS # --OR-- LS=$(type -P ls) if [ -x $LS ]; then : commands involving $LS here fi
If you need to look in a variety of locations, possibly including
the $PATH
, use a for loop. To search
the $PATH
, use the variable
substitution operator ${variable/pattern/
replacement}
to replace the : separator with a space, and then
use for as usual. To search the $PATH
and other possible locations, just list them:
for path in ${PATH//:/ }; do [ -x "$path/ls" ] && $path/ls done # --OR-- for path in ${PATH//:/ } /opt/foo/bin /opt/bar/bin; do [ -x "$path/ls" ] && $path/ls done
If the file is not in the $PATH
, but could be in a list of locations, possibly even under different names, list the entire path and name: ...
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.