How do you go up the parent directory structure of a bash script?

Is there a faster way to go up several directory levels from a script location.

This is what I have.

# get the full path of the script
D=$(cd ${0%/*} && echo $PWD/${0##*/})

D=$(dirname $D)
D=$(dirname $D)
D=$(dirname $D)

# second level parent directory of script
echo $D

I would like a neat way to find the nth level. Any ideas other than putting in a for loop?

+5
source share
7 answers
dir="/path/to/somewhere/interesting"
saveIFS=$IFS
IFS='/'
parts=($dir)
IFS=$saveIFS
level=${parts[3]}
echo "$level"    # output: somewhere
+5
source
#!/bin/sh
ancestor() {
  local n=${1:-1}
  (for ((; n != 0; n--)); do cd $(dirname ${PWD}); done; pwd)
}

Using:

 $ pwd
 /home/nix/a/b/c/d/e/f/g

 $ ancestor 3
 /home/nix/a/b/c/d
+2
source

Perl:

$ pwd
/u1/myuser/dir3/dir4/dir5/dir6/dir7

, N ( 5)

$ perl-e 'use File::Spec; \
          my @dirs = File::Spec->splitdir( \
             File::Spec->rel2abs( File::Spec->curdir() ) ); \
          my @dirs2=@dirs[0..5]; print File::Spec->catdir(@dirs2) . "\n";'
/u1/myuser/dir3/dir4/dir5

N ( 5) ( , ).

$ perl -e 'use File::Spec; \
           my @dirs = File::Spec->splitdir( \
              File::Spec->rel2abs( File::Spec->curdir() ) ); \
           my @dirs2=@dirs[0..$#dir-5]; print File::Spec->catdir(@dirs2)."\n";'
/u1/myuser

bash script, :

D=$(perl -e 'use File::Spec; \
           my @dirs = File::Spec->splitdir( \
              File::Spec->rel2abs( File::Spec->curdir() ) ); \
           my @dirs2=@dirs[0..$#dir-5]; print File::Spec->catdir(@dirs2)."\n";')
+1

, for?

, regexp, glob. glob - .

BTW, : echo $(cd $PWD/../.. && echo $PWD), /../.. .

Perl, :

perl -e '$ENV{PWD} =~ m@^(.*)(/[^/]+){2}$@ && print $1,"\n"'

{2} Perl - , . :

N=2
perl -e '$ENV{PWD} =~ m@^(.*)(/[^/]+){'$N'}$@ && print $1,"\n"'

Perl split(), join ( ) splice() , :

perl -e '@a=split("/", $ENV{PWD}); print join("/", splice(@a, 0, -2)),"\n"'

-2 , .

+1

. script, .

rtrav() { test -e $2/$1 && echo $2 || { test $2 != / && rtrav $1 `dirname $2`;}; }

, GIT: rtrav .git $PWD

rtrav , , . , , .

(test -e $2/$1) , .

+1

script:

echo "$(readlink -f -- "$(dirname -- "$0")/../..")"

-- .

0

perl script... TIMTOWTDI $RunDir , ...

        #resolve the run dir where this scripts is placed
        $0 =~ m/^(.*)(\\|\/)(.*)\.([a-z]*)/; 
        $RunDir = $1 ; 
        #change the \ to / if we are on Windows
        $RunDir =~s/\\/\//gi ; 
        my @DirParts = split ('/' , $RunDir) ; 
        for (my $count=0; $count < 4; $count++) {   pop @DirParts ;     }

        $confHolder->{'ProductBaseDir'} = $ProductBaseDir ; 
0

All Articles