How to expand relative paths in shell script

前端 未结 7 1251
春和景丽
春和景丽 2021-02-06 21:49

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         


        
7条回答
  •  醉话见心
    2021-02-06 22:51

    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)
    

提交回复
热议问题