Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create relative path from absolute path in bash? [duplicate]

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?

like image 208
Michal Špondr Avatar asked Oct 18 '25 06:10

Michal Špondr


1 Answers

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

like image 52
oliv Avatar answered Oct 19 '25 22:10

oliv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!