Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

linux - How to expand relative paths in shell script

I am writing a script to set environment variables on linux 2.6 using bash. So the script contains commands like:

export SRC_DIR=..
export LIBPATH=${SRC_DIR}/lib

the problem is that when i try to do echo $LIBPATH, it shows "../lib" as opposed to expanding the SRC_DIR to full path. I would really like the script to print something like /home/x/lib as opposed to ../lib.

UPDATE The script should evaluate SRC_DIR to be one directory upwards from the script's location and not the current directory from where the script is invoked

question from:https://stackoverflow.com/questions/11621639/how-to-expand-relative-paths-in-shell-script

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Change Directory in Subshell

There's a little trick you can use to get the absolute path from a relative path without changing the present working directory. The trick is to move to the relative path in a subshell, and then expand the working directory. For example:

export SRC_DIR=$(cd ..; pwd)

Relative Paths from Script Instead of Invocation Directory

To change to a relative path from a script's location, rather than the current working directory, you can use a parameter expansion or the dirname utility. I prefer dirname, since it's a little more explicit. Here are both examples.

# Using /usr/bin/dirname.
export SRC_DIR=$(cd "$(dirname "$0")/.."; pwd)

# Using the "remove matching suffix pattern" parameter expansion.
export SRC_DIR=$(cd "${0%/*}/.."; pwd)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...