How to convert the ..
in the path names to absolute path names in a bash script. That is, if I have a path /home/nohsib/dvc/../bop
, I want this to be changed to the path without dots in it, in this case /home/nohsib/bop
How can I do that?
The absolutePath function works by beginning at the starting folder and moving up one level for each "../" in the relative path. Then it concatenates the changed starting folder with the relative path to produce the equivalent absolute path.
In this case, first, we need the current script's path, and from it, we use dirname to get the directory path of the script file. Once we have that, we cd into the folder and print the working directory. To get the full or absolute path, we attach the basename of the script file to the directory path or $DIR_PATH.
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.
so using $PWD is the absolute path of where you are so you get the output as absolute. If you rely on PWD , you could simply use $PWD/$filename .
What you're looking for is readlink
:
absolute_path=$(readlink -m /home/nohsib/dvc/../bop)
Please note: You need to use GNU's readlink
implementation which offers the "-m" option. BSD's readlink
for example does not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With