0

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

Community
  • 1
  • 1
PJConnol
  • 119
  • 1
  • 9
  • This is a very confusing description, and I'm not sure what you're asking. Are you saying (in your last line) that you need to remember a directory, to be able to switch back to it later? If so, `$OLDPWD` saves the prior value of `$PWD`. But it might be better for you to post some code to show what you're trying to do, what you expect to happen, and where it fails if you got that far. – gilez Sep 27 '16 at 16:34
  • Do you just want a relative path, as in `grep -rnw 'sample text' ../..`? – ccarton Sep 27 '16 at 19:03
  • Apologies that last line I wrote is stupid, I simply just want to access ../program-directory with the example.bash script – PJConnol Sep 28 '16 at 08:28
  • @ccarton Yes I think so – PJConnol Sep 28 '16 at 08:34

1 Answers1

1

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

HASSeering
  • 166
  • 1
  • 9