Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert ".." in path names to absolute name in a bash script?

Tags:

linux

bash

unix

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?

like image 865
Nohsib Avatar asked Jul 10 '11 21:07

Nohsib


People also ask

How do you convert relative path to absolute path?

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.

How do you set an absolute path in bash?

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.

What does [- Z $1 mean in bash?

$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.

Which command gets the absolute path for any path in shell scripting?

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 .


1 Answers

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.

like image 76
Martin Avatar answered Sep 29 '22 05:09

Martin