Convert relative paths to absolute paths using shell Functions

Source: Internet
Author: User

There are many methods to convert relative paths to absolute paths. I don't know if there are any ready-made bash commands. I wrote a script first, which is also counted as practice shell programming.

At that time, I thought of the first method, that is, to determine whether it is a directory. If it is a directory, call the CD command, and then take the return value of the PWD command. If it is a file, remove the file name, then, call the CD command to obtain its directory value and then combine it. However, a condition for calling the CD command here is that the directory must exist. therefore, I have optimized this method:

Call method: get_fullpathRelative_path

Get_fullpath ()
{

# Determine whether a parameter exists. For example, if the current path is/home/user1/workspace, the parameter is./../DIR/Hello. C.
If [-Z $1]
Then
Return 1
Fi
Relative_path = $1

# Retrieve the first part of the Directory, such. /.. /.. /,.. /.. /, etc. Here, call the CD command to obtain the absolute path of this part of the path, because the upper-level directory of the current path certainly exists.

# Tmp_path1 is ./..

# Tmp_fullpath1/home/user1

Tmp_path1 =h1 (echo $ relative_path | sed-e "s =/[^ \.] * $ = ")
Tmp_fullpath1 = $ (CD $ tmp_path1; PWD)

# Obtain the following path

# Tmp_path2: Dir/Hello. c

Tmp_path2 = $ (echo $ relative_path | sed-e "s = \. [\./] * [/| $] = ")

# Return the patchwork path
Echo $ {tmp_fullpath1}/$ {tmp_path2}
Return 0
}

I can see that KSh has a whence command on the Internet, but I haven't found it in bash.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.