System Administration Technical

Pattern for setting root paths in a bash binary

I find myself constantly seeking to set up a coding pattern where I have a project (say, a web application) which has root directories such as:

  • bin
  • public
  • classes
  • theme
  • vendor/bin
  • etc

etc. where various resources for our application are stored. What is essential is that that sometimes there are multiple versions of an application running on the same server at the same time. You want each application to be configured independently, and you want it to depend only on the codebase it’s a part of.

That said, to do this you set a “marker” in your bash scripts which allow you to refer to other directories from the application root.

The pattern is this, say for a file in bin/

export APPLICATION_ROOT="$(cd $(dirname "$BASH_SOURCE")/..; pwd)"

Later in that shell script, I can refer to the resources using the $APPLICATION_ROOT variable.

I’ve tried various techniques to determine the real path of the bash script, the above seems to work consistently and across systems (Ubuntu, Debian, CentOS, and FreeBSD.)

A sample stub script from running PHP Unit tests, for example:

export APPLICATION_ROOT="$(cd $(dirname "$BASH_SOURCE")/..; pwd)"

if [ ! -x "$bindir/phpunit" ]; then
        echo "$bindir/phpunit binary is not set up correctly, need to run:" 1>&2
        echo 1>&2
        echo '    composer install && vendor/bin/zesk update' 1>&2
        echo 1>&2
        exit 1
$bindir/phpunit $@