Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expand relative paths in shell script

Tags:

linux

bash

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

like image 700
Jimm Avatar asked Jul 23 '12 22:07

Jimm


1 Answers

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) 
like image 119
Todd A. Jacobs Avatar answered Sep 22 '22 20:09

Todd A. Jacobs