In case you need to get the absolute path to the folder in which a bash script exists (e.g. when you need to refer to a relative binary), you can do it like this:

myscript.sh

#!/usr/bin/env bash

SCRIPTPATH="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
echo $SCRIPTPATH

So, if you run the script, you will get:

$ ./subfolder/myscript.sh
/Users/user/bin/subfolder

You can then use it to easily refer to a relative binary or file in a reliable way. We use this to create a script which uses xcodebuild but applies xcbeautify to it's output. As we are using a custom build of xcbeautify and have it in the same folder as the script, this trick becomes really handy:

xcodebuild.sh

#!/usr/bin/env bash

SCRIPTPATH="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
PRETTIER=$SCRIPTPATH/xcbeautify

set -o pipefail && xcodebuild "$@" | $PRETTIER --disable-colored-output

exit $?

Related Posts

  • SSH Tunnel
  • Checking websockets with cURL
  • Installing Packages from a file on Linux
  • TIL: combining PDF files via the command line
  • Version info with otool