检查目录是否以递归方式反转路径

时间:2012-07-05 21:41:24

标签: regex bash sed awk

我有点困惑!我不知道如何提出这个问题。

可能有一个例子。

我正在编写一个bash脚本,用于检查当前目录中是否有名为“FNS”的特定文件夹。要检查文件是否存在,我会这样做。

        FOLDER=FNS
        if [ -f $FOLDER ];
        then
        echo "File $FOLDER exists"
        else
        # do the thing
        fi

问题出现如果文件不存在!我希望脚本记下当前路径并移回目录[我的意思是cd ..在命令行中,我不确定我是否在这里使用正确的词汇表]并检查文件是否存在,如果不存在,再向后退一步,直到它所在的目录显示[它肯定存在]。当找到将路径存储在变量中时。 执行的当前目录不应该更改。我尝试将pwd传递给变量并切换到最后一个斜线和其他一些东西但没有成功!

希望我能在这方面做点什么。 像往常一样建议,算法和解决方案是受欢迎的:)

5 个答案:

答案 0 :(得分:2)

试试这个,括号启动一个子shell,这样cd命令就不会改变当前shell的当前目录

(while [ ! -d "$FOLDER" ];do cd ..;done;pwd)

答案 1 :(得分:1)

bash pushd popd 内置命令可以为您提供帮助。 在伪代码中:

function FolderExists() { ... }

cds = 0
while (NOT FolderExists) {
    pushd ..
    cds=cds+1;
}

store actual dir using pwd command

for(i=0;i<cds;i++) {
    popd
}

答案 2 :(得分:1)

使用perl的一种方式。

script.pl的内容(该目录是硬编码的,但很容易修改程序以将其作为参数读取):

use warnings;
use strict;
use File::Spec;
use List::Util qw|first|;

## This variable sets to 1 after searching in the root directory.
my $try;

## Original dir to begin searching.
my $dir = File::Spec->rel2abs( shift ) or die;

do {
    ## Check if dir 'FNS' exists in current directory. Print
    ## absolute dir and finish in that case.
    my $d = first { -d && m|/FNS$| } <$dir/*>;
    if ( $d ) { 
        printf qq|%s\n|, File::Spec->rel2abs( $d );    
        exit 0;
    }   

    ## Otherwise, goto up directory and carry on the search until
    ## we reach to root directory.
    my @dirs = File::Spec->splitdir( $dir );
    $dir = File::Spec->catdir( @dirs[0 .. ( $#dirs - 1 || 0 )] )
} while ( $dir ne File::Spec->rootdir || $try++ == 0);

使用将开始搜索的目录运行它。它可以是相对或绝对路径。像这样:

perl script.pl /home/birei/temp/dev/everychat/

perl script.pl .

如果找到目录,它将打印绝对路径。我的测试的一个例子:

/home/birei/temp/FNS

答案 3 :(得分:1)

#!/bin/bash
dir=/path/to/starting/dir    # or $PWD perhaps
seekdir=FNS

while [[ ! -d $dir/$seekdir ]]
do
    if [[ -z $dir ]]    # at /
    then
        if [[ -d $dir/$seekdir ]]
        then
            break    # found in /
        else
            echo "Directory $seekdir not found"
            exit 1
        fi
    fi
    dir=${dir%/*}
done

echo "Directory $seekdir exists in $dir"

请注意,-f测试适用于常规文件。如果要测试目录,请使用-d

答案 4 :(得分:1)

    #!/bin/bash

FOLDER="FNS"
FPATH="${PWD}"
P="../"

if [ -d ${FOLDER} ];

then 

    FPATH="$(readlink -f ${FOLDER})"
    FOLDER="${FPATH}"
    echo "FNS: " $FPATH

else

    while [ "${FOLDER}" != "${FPATH}" ] ; do
    NEXT="${P}${FOLDER}"    

    if [ -d "${NEXT}" ];
    then
        FPATH=$(readlink -f ${NEXT})
        FOLDER="${FPATH}"
        echo "FNS: " $FPATH
    else
        P="../${P}"
    fi

    done

fi
相关问题