Check if a directory exists recursively reversing the path
I am kind of confused here ! I am not sure how to put forth the question .
May be with an example .
I am in the process of writing a bash script which checks if a specific folder named "FNS" is in the current directory . To check if the file exists ,I do this.
FOLDER=FNS
if [ -f $FOLDER ];
then
echo "File $FOLDER exists"
else
# do the thing
fi
The problem arises If the file doesnt exists ! I want the script to take a note of the current path and move back a directory [ I meant cd .. in the command line ,I am not sure if I am using the correct vocabulary here] and check if the file exists and if not, again move back one step, until the directory in which it exist shows up [ it is sure to exist ] .When found store the path in a variable . The present directory of execution should not change.I tried passing the pwd
to a variable and cutting till the last slash and some other stuffs without success !
Hope I can do something in this regard . Like always suggestions,algorithms and work arounds are welcome :)
试试这个,用圆括号启动一个子shell,这样cd命令不会改变当前shell的当前目录
(while [ ! -d "$FOLDER" ];do cd ..;done;pwd)
The bash pushd and popd built-in commands could help you. In pseudocode:
function FolderExists() { ... }
cds = 0
while (NOT FolderExists) {
pushd ..
cds=cds+1;
}
store actual dir using pwd command
for(i=0;i<cds;i++) {
popd
}
One way using perl
.
Content of script.pl
(the directory is hard-coded but it's easy to modify the program to read it as an argument):
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|%sn|, 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);
Run it with a directory where the search will begin. It can be relative or absolute path. Like this:
perl script.pl /home/birei/temp/dev/everychat/
or
perl script.pl .
It will print the absolute path if found the directory. An example of my test:
/home/birei/temp/FNS
链接地址: http://www.djcxy.com/p/97116.html
下一篇: 检查一个目录是否递归地反转路径