PJConnol PJConnol - 24 days ago 5x
Linux Question

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


But then the user downloads the program files in
creating a situation where we have

Then I have a bash script that runs in

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

Is there any simple way in one line I can grep in
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
from a script called in a sub-directory of


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).