How to find the deepest path that exists in Bash
When I get an error like:
$ ls /var开发者_StackOverflow/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.
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/
Try:
FILE="/var/django-projects/daks/public/media/uploads/bandsaws/sneaks.jpg"
while true; do [ -e "$FILE" ] && break || FILE=$(dirname "$FILE"); done; echo $FILE
#!/bin/bash
function firstValidParent () {
d="$1"
[ -e "${d}" ] && echo $d || firstValidParent "${d%/*}"
}
精彩评论