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

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

问题描述

假设:

some.txt
dir
 |-cat.sh

使用具有内容cat.sh:

With cat.sh having the content:

cat ../some.txt

然后运行 ./ cat.sh 运行时 DIR 工作正常./ DIR / cat.sh 在同一水平上的 DIR 没有。我希望这是由于不同的工作目录。有一个简单的是使路径 ../ 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 the different working directories. Is there an easy was 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}")" ; pwd -P )

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

这将使独立你来自哪里,它调用你的shell脚本工作。每次运行它​​的时候,它会像如果你正在运行 ./ cat.sh DIR

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天全站免登陆