Search code examples
shellunixsedpathpwd

Path of the current, parents and root directory


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/\\/[^\\/]*$//

Solution

  • 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