简体   繁体   中英

Bash ~ Access directory that may change, from script within sub-directories of directory

I'm a bit new to bash and its workings but I am wondering is there anyway in bash to access a directory that may change in its address due to where the user installs it in bash. (This happens all the time, so there must be)

For example: I have a program that has the directory of ../program-directory/..

But then the user downloads the program files in /extra-directory/ creating a situation where we have /extradirectory/program-directory

Then I have a bash script that runs in ../program-directory/script-directory/script/example.bash

I would then like to grep -rnw 'sample text' /program-directory from the example.bash script

Is there any simple way in one line I can grep in program-directory without the hassle of where the user installed this program

FYI, I have looked at Can a Bash script tell which directory it is stored in? but I need to grep in ../program-directory from a script called in a sub-directory of ../program-directory

If your program is in /some/example/dir/program-directory/script-directory/script/example.bash and you want to run grep on the file /some/example/dir/program-directory/sample.txt then you write in bash code:

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

there are many variants of the code above with the same meaning or slightly altered meaning. This code is written for clarity and correct handling of directory names with spaces and special characters. This code ignores the currend working directory on purpose (which is what you wanted as far as I can tell).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM