当我收到如下错误时:
$ 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
我希望能够问what-is-the-deepest-path-that-does-exists
然后回来,说:
/var/django-projects/daks/public/media/
我认为可以通过在每次迭代中添加../
的循环来完成,并在找到存在的路径时退出。
答案 0 :(得分:5)
您可能会发现dirname
有用。例如:
f=/var/django-projects/daks/public/media/uploads/bandsaws/sneaks.jpg
until [ -e "$f" ]; do f=$(dirname "$f"); done
echo $f
应该给你/var/django-projects/daks/public/media/
答案 1 :(得分:2)
尝试:
FILE="/var/django-projects/daks/public/media/uploads/bandsaws/sneaks.jpg"
while true; do [ -e "$FILE" ] && break || FILE=$(dirname "$FILE"); done; echo $FILE
答案 2 :(得分:1)
#!/bin/bash
function firstValidParent () {
d="$1"
[ -e "${d}" ] && echo $d || firstValidParent "${d%/*}"
}