基于文件位置而不是当前工作目录的相对路径 [英] Relative paths based on file location instead of current working directory

查看:88
本文介绍了基于文件位置而不是当前工作目录的相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出:

some.txt
dir
 |-cat.sh

cat.sh具有以下内容:

With cat.sh having the content:

cat ../some.txt

然后在dir内运行./cat.sh可以正常工作,而在与dir相同级别上运行./dir/cat.sh则可以.我希望这归因于不同的工作目录.有没有一种简单的方法可以使路径../some.txt相对于cat.sh的位置?

Then running ./cat.sh inside dir works fine while running ./dir/cat.sh on the same level as dir does not. I expect this to be due to the different working directories. Is there an easy way to make the path ../some.txt relative to the location of cat.sh?

推荐答案

您要做的是获取脚本的绝对路径(可通过${BASH_SOURCE[0]}获得),然后使用它来获取父目录和cd脚本开头的内容.

What you want to do is get the absolute path of the script (available via ${BASH_SOURCE[0]}) and then use this to get the parent directory and cd to it at the beginning of the script.

#!/bin/bash
parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )

cd "$parent_path"
cat ../some.text

这将使您的shell脚本独立于您从何处调用它而工作.每次运行它时,就像在dir中运行./cat.sh一样.

This will make your shell script work independent of where you invoke it from. Each time you run it, it will be as if you were running ./cat.sh inside dir.

请注意,此脚本仅在您直接调用脚本(即不通过符号链接)时才有效,否则,找到脚本的当前位置会更加棘手)

Note that this script only works if you're invoking the script directly (i.e. not via a symlink), otherwise the finding the current location of the script gets a little more tricky)

这篇关于基于文件位置而不是当前工作目录的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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