Bash: search up a directory tree

This should work but tell me if it needs compatibility with POSIX. The advantage of this is that you don't need to change your directory to higher level just to make the search, and also no need to use a subshell.

#!/bin/bash

search_up() {
    local look=${PWD%/}

    while [[ -n $look ]]; do
        [[ -e $look/$1 ]] && {
            printf '%s\n' "$look"
            return
        }

        look=${look%/*}
    done

    [[ -e /$1 ]] && echo /
}

search_up "$1"

Example:

bash script.sh /usr/local/bin

Output:

/

For the record, here is what I ended up using:

while [ $PWD != "/" ]; do test -e tools/bin && { pwd; break; }; cd .. ; done

Similar to my OP, but in the end I was able to drop the subshell parentheses () completely, because this line is itself invoked using the "shell" command from another program. Hence also stuffing it all onto one line.

I still liked KonsoleBox's well-reasoned answer as a possibly more general solution, so I'm accepting that.

Tags:

Shell

Bash