How to expand relative paths in shell script

前端 未结 7 1337
春和景丽
春和景丽 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:35

    The readlink command is capable of not only resolving symlinks, but also canonicalizing relative paths. Be careful, since you may not want the behaviour of resolving symlinks in all your scripts. If you don't want to resolve symlinks, pwd would be the best; note the use of a subshell, so the cd command does not affect the working directory in the main shell.

    # The path you want to get information on... (for readability)
    your_path=..
    
    # Using /bin/readlink (resolves symlinks)
    export SRC_DIR=$(readlink --canonicalize $your_path)
    
    # Using /usr/bin/dirname (keeps symlinks)
    export SRC_DIR=$(cd $your_path ; pwd)
    

提交回复
热议问题