linux - Bash ~ 从目录的子目录中的脚本访问可能更改的目录

标签 linux bash scripting grep directory

我对 bash 及其工作方式有点陌生,但我想知道在 bash 中是否有访问一个目录的地址可能会因用户在 bash 中的安装位置而改变。 (这种事经常发生,所以一定有)

例如: 我有一个程序,其目录为 ../program-directory/..

但是随后用户将程序文件下载到 /extra-directory/ 中,造成我们有 /extradirectory/program-directory

然后我有一个运行在 ../program-directory/script-directory/script/example.bash

中的 bash 脚本

然后我想从 example.bash 脚本中 grep -rnw 'sample text'/program-directory

是否有任何简单的方法可以在 program-directory 中 grep 一行,而无需用户安装此程序的位置

仅供引用,我看过Can a Bash script tell which directory it is stored in?但我需要从 ../program-directory

的子目录中调用的脚本在 ../program-directory 中进行 grep

最佳答案

如果你的程序在 /some/example/dir/program-directory/script-directory/script/example.bash 并且你想运行 grep文件 /some/example/dir/program-directory/sample.txt 然后你用 bash 代码写:

main() {
    local DIR="$(dirname "$0")"
    local DIR="$(cd "${DIR}" && pwd)"
    cd "${DIR}"
    grep 'search term' -- ../../sample.txt
}

上述代码有许多变体,具有相同的含义或略有不同的含义。编写此代码是为了清晰和正确处理包含空格和特殊字符的目录名称。此代码故意忽略当前工作目录(据我所知这是您想要的)。

关于linux - Bash ~ 从目录的子目录中的脚本访问可能更改的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39728477/

相关文章:

linux - Cassandra - 无法删除行

Bash:如果不存在,如何在行尾添加字符?

linux - 生成 : How to pass arguments to spawn within an expect script?

bash - IO::Uncompress::Gunzip 在 "original"gzipped 文件内的第一个 "concatenated"gzipped 文件后停止

linux - 从目录层次结构中的文件递归搜索和输出字符串

c - 实现系统调用而不显式调用它们

c - 使用 2 个 c 文件的 Linux 命令行重定向

linux - CSV 文件输出重新格式化

bash - 如何在 Ansible Jinja2 (.j2) 模板中指定 "if else"语句?

windows - GO 可以用作应用程序中的脚本引擎吗?