Tom Viner
Tom Viner

Reputation: 6783

How to find the deepest path that exists in Bash

When I get an error like:

$ ls /var/django-projects/daks/public/media/uploads/bandsaws/sneaks.jpg
ls: /var/django-projects/daks/public/media/uploads/bandsaws/sneaks.jpg: No such file or directory

I'd like to be able to ask what-is-the-deepest-path-that-does-exists and get back, say:

/var/django-projects/daks/public/media/

I think it could be done with a loop that added ../ on each iteration and quitted when a path that exists was found.

Upvotes: 1

Views: 403

Answers (3)

user unknown
user unknown

Reputation: 36229

#!/bin/bash
function firstValidParent () { 
    d="$1"
    [ -e "${d}" ] && echo $d || firstValidParent "${d%/*}"
}

Upvotes: 1

jpnp
jpnp

Reputation: 1390

You may well find dirname useful. Something such as:

f=/var/django-projects/daks/public/media/uploads/bandsaws/sneaks.jpg

until [ -e "$f" ]; do f=$(dirname "$f"); done

echo $f

should give you /var/django-projects/daks/public/media/

Upvotes: 5

Michał Šrajer
Michał Šrajer

Reputation: 31182

Try:

FILE="/var/django-projects/daks/public/media/uploads/bandsaws/sneaks.jpg"
while true; do [ -e "$FILE" ] && break || FILE=$(dirname "$FILE"); done; echo $FILE

Upvotes: 2

Related Questions