且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

壳牌:基于文件的位置,而不是当前工作目录的相对路径

更新时间:2022-01-19 22:25:09

您想要做的是通过 $ {BASH_SOURCE [0]} $ C拿到剧本的绝对路径(可$ C>),然后用它来获取父目录和 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)