Search code examples
regexbashsedrelative-pathpwd

How to create relative path from absolute path in bash?


I am in this directory:

/home/michal/project/test/my-utils/rel/0.1.0

and I would like to get the relative path to /home/michal/project/ in Linux shell:

../../..

I've tried something with sed but I did not succeeded in creating the regular expression. E.g. one of the attempts:

pwd | sed -e "s/.*project\///g" | sed -e "s/[^\/]+/../g"

Any tips how to do it?


Solution

  • You can use the command realpath:

    realpath --relative-to=${PWD} /home/michal/project/
    

    from the help page:

    --relative-to=FILE print the resolved path relative to FILE