如何找到Bash中存在的最深的路径

时间:2011-08-04 10:08:12

标签: bash

当我收到如下错误时:

$ 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/

我认为可以通过在每次迭代中添加../的循环来完成,并在找到存在的路径时退出。

3 个答案:

答案 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%/*}"
}