如何在Shell脚本中扩展相对路径 [英] How to expand relative paths in shell script

查看:59
本文介绍了如何在Shell脚本中扩展相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本,使用bash在linux 2.6上设置环境变量.因此该脚本包含以下命令:

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

问题是当我尝试执行$ LIBPATH时,它显示为"../lib",而不是将SRC_DIR扩展为完整路径.我真的希望脚本打印类似/home/x/lib而不是../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.

更新脚本应将SRC_DIR评估为脚本位置上方的一个目录,而不是调用脚本的当前目录

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

推荐答案

更改Subshel​​l中的目录

您可以使用一些技巧来从相对路径获取绝对路径,而无需更改当前的工作目录.诀窍是移至子shell中的相对路径,然后展开工作目录.例如:

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)

这篇关于如何在Shell脚本中扩展相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆