2012-07-05 122 views
1

我有点困惑在这里!我不知道如何提出这个问题。检查一个目录是否存在递归反转路径

可能是一个例子。

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

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

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

希望我能在这方面做点什么。 像往常一样建议,算法和变通,欢迎:)

+1

你需要建立自己的脚本的当前目录?使用'find'命令对你没有用处? – Ander2 2012-07-05 21:45:35

+0

@Ander2:'find -maxdepth 1'将是相同的,没有'-maxdepth',如果你只想沿着一个目录链查看,它可能会太慢。 – 2012-07-05 22:52:02

回答

2

试试这个,用括号启动子shell这样的cd命令不改变当前的shell

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

+1:请注意,应该用包含FNS的目录中必须执行的任何操作替换pwd,因为当子shell退出时,位置(以及任何分配的变量的值)将会丢失。只需用调用函数来替换'pwd'即可。 – 2012-07-06 13:40:41

+0

或者:'WD = $(while!测试-d $ FOLDER;做CD ..;完成; pwd)' – 2012-07-06 16:13:40

1

bash的PUSHDPOPD内置的命令可以帮助你。 伪代码:使用perl

function FolderExists() { ... } 

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

store actual dir using pwd command 

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

的一种方式。的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 
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

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