Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there a neater way of climbing up multiple directory levels from the location of a script.

This is what I currently 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 of finding the nth level. Any ideas other than putting in a for loop?

like image 387
froogz3301 Avatar asked Aug 27 '10 14:08

froogz3301


Video Answer


2 Answers

dir="/path/to/somewhere/interesting"
saveIFS=$IFS
IFS='/'
parts=($dir)
IFS=$saveIFS
level=${parts[3]}
echo "$level"    # output: somewhere
like image 71
Dennis Williamson Avatar answered Nov 14 '22 16:11

Dennis Williamson


#!/bin/sh
ancestor() {
  local n=${1:-1}
  (for ((; n != 0; n--)); do cd $(dirname ${PWD}); done; pwd)
}

Usage:

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

 $ ancestor 3
 /home/nix/a/b/c/d
like image 35
nix Avatar answered Nov 14 '22 16:11

nix