bug-findutils
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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


From: Bernhard Voelker
Subject: Re: recursive find in current and parent etc until an item is found
Date: Fri, 10 Apr 2020 17:37:34 +0200
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Thunderbird/68.6.0

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



reply via email to

[Prev in Thread] Current Thread [Next in Thread]