Re: recursive find in current and parent etc until an item is found

Peng Yu <[email protected]>
Newsgroups gmane.comp.gnu.findutils.bugs
Message-ID <CABrM6wkX3QJh2hd44h23YcE-74xP9e1=hp9xTAF1dNRPVrmicw@mail.gmail.com>
Thanks. I will need to search the parent directory recursively. Does
this code only search whether a file is in a parent their parents,
etc., but not recursively for a given ancestor?

On 4/10/20, Bernhard Voelker <[email protected]> wrote:
> On 2020-04-10 16:09, Peng Yu wrote:
>> Hi,
>>
>> I'd like to look for a file by its name in the current directory. If
>> not found, go the the parent and look for it again. If not go up one
>> level again and look for it, ... until it is found (or until a given
>> level is reached). If the file is not found, return an error.
>>
>> The resulted path should be relative to the original current directory.
>>
>> Is there a way to do this easily with find? Thanks.
>
> Hi Peng,
>
> I'm afraid find(1) is only searching "down" the current hierarchy, but
> not "up" until "/".  However once would involve find(1) here, it would
> just be degraded to testing whether the file exist.
> Instead, I'd go with a shell script like this:
>
> ---8<---8<---8<---8<---8<---8<---8<---8<---8<---8<---8<---
> #!/bin/sh
>
> f="$1" \
>   && test -n "$f" \
>   || { echo "Usage: $0 FILE" >&2; exit 1; }
>
> p="."
>
> # Search until the parent is identical to the current directory (='/').
> until [ "$p" -ef "$p/.." ]; do
>   if [ -e "$p/$f" ]; then
>     echo "$p/$f"
>     exit 0
>   fi
>   p="$p/.."
> done
>
> # Now we're in the '/' dir; check once again.
> if [ -e "$p/$f" ]; then
>   echo "$p/$f"
>   exit 0
> fi
>
> echo "'$f' not found" >&2
> exit 1
> --->8--->8--->8--->8--->8--->8--->8--->8--->8--->8--->8---
>
> Have a nice day,
> Berny
>


-- 
Regards,
Peng
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.