0

There are several configuration files and bash scripts within our git repo code set that need to set directory paths. They should all root from where the repo is located. In other words, I put my repo at /home/userMe but you put it at /home/userYou/code/.

How can the bash scripts be structured such that they either:

  • don't have to be edited to localized the root directory?
  • or there is one script which is run first that localizes?
dacracot
  • 22,002
  • 26
  • 104
  • 152

1 Answers1

0

The common way to do this is for scripts to know where they are located, for example using dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd). That way, each script which has to refer to another script in the same repository can do so by using "${dir}/foo/bar" style paths for files in the same part of the tree and "$(dirname -- "$(dirname -- "$dir")")/foo/bar" for files with the same grandparent directory. This is necessary (but not necessarily sufficient) to make your scripts executable from anywhere.

You can of course source a script at the top level of the repository which does the same thing. That's actually more complicated, however, since each script still has to be able to locate that script relative to itself, at which point it might as well know its own location.

l0b0
  • 55,365
  • 30
  • 138
  • 223
  • I like DIR=$(dirname $0), it's much simpler and readability is improved. – Michael Aug 01 '15 at 15:14
  • @Michael In Bash, more than most languages, the portable and secure way of doing things is usually much uglier than the simplest thing that can work in any situation. For example, [`dirname $0` doesn't work if there are spaces anywhere in the path](http://mywiki.wooledge.org/WordSplitting). And if you're writing a script for others to run from arbitrary locations (like OP) you really want to make it difficult to break. – l0b0 Aug 01 '15 at 16:26
  • well if you use `dirname "$0"` it works with spaces. – Michael Aug 01 '15 at 16:36