Path of the current, parents and root directory

1.2k views Asked by At

I need to print the path of the current, parent and root directory in UNIX. I can use commands, or a shell script. I managed to do that for the current and the parent directory, but I do not know how to print it for the root directory.

Here is what i have done:

  • current: pwd
  • parent: echo $(pwd) | sed -e s/\\/[^\\/]*$//
3

There are 3 answers

9
josifoski On BEST ANSWER

gnu sed

echo $(pwd) | sed -r -e 'p; :a; s#(.*)/.*#\1#; H; ta; x' | sed '/^$/d'  

this will print all directories from current -> root

it uses greedy search for '/' keeping only left part, appending in hold space, ta is conditional branch for substutution, so if there is one it branches to :a, at the end x is swaping hold space to pattern space.
Last sed command is for clearing empty lines

5
NeronLeVelu On

Same idea as @josifoski

pwd | sed ':a;\#/\(.*\)/[^/]*# {p;s##/\1#;ba}'

Print and cycle until only 1st folder name, removing every cycle the last folder of the path

0
bkmoney On

I think it's easier to do this using awk:

echo $(pwd) | awk 'BEGIN {FS=OFS="/"} {l=NF; while (i++<l-1) {print; NF--}}'

Explanation

This will print all directories from current --> root. It does this by printing the line, then decrementing the NF, the number of fields. Notice that I have set both the input and output field separators to the /.