A Posix function for finding the nearest parent file. For example "what .git/ am I working in?" or "is there an .npmrc affecting npm
from this path?"
This implementation specifically follows the symbolic links toward root rather than the canonical path.
Looking for improvements and potential edge cases.
lsup() {
path="$1";
file="$2";
if [ -z "${file}" ]; then
file="${path}";
path="$(pwd)";
fi;
path="$(realpath -es "${path}")"
[ -n "${SH_DEBUG}" ] && echo "Searching for ${file} from ${path}…";
while [ "${path}" != "/" ]; do
[ -e "${path}/${file}" ] && break;
[ -n "${SH_DEBUG}" ] && echo "Not found in ${path}";
path="$(realpath -s "${path}/..")";
done;
[ -e "${path}/${file}" ] && echo "${path}/${file}" || return 1;
}
https://gist.github.com/psaxton/6937fec3357f8295828d2e3577f9bcb6
Used as:
> lsup .git
> lsup /path/to/check .npmrc
local
if your shell supports that, or else changed to have more specific names which are less likely to clash with user variables with the same names. E.g._lsup_path
and_lsup_file
would be quite a lot uglier, but correspondingly safer if you don't havelocal
. \$\endgroup\$realpath
is not in POSIX (detailed link: utilities section). unix.stackexchange.com/questions/101080/… suggestsreadlink -f
\$\endgroup\$