Get the absolute path in a bash script. Linux and BSD/Mac

¿Have you ever needed to get the absolute path to a script in a bash script? Here I explain how to set in a variable the current absolute path to the executed script and to its folder as well.

When it comes to development I work under Mac, but when I publish my work I do it usually under Linux. It happens sometimes to me that I create bash scripts that don't work in one or the other system. If you want to get the current script path one could think that the pwd command is enough, but that's not true if you launch your script from anywhere else but the location folder.

In Linux environments you can use the readlink command. The problem is that in BSD systems and in Linux the implementation of this function is quite different. If you don't mind backwards compatibility with Mac you can get the current script path with the command:

SCRIPT_PATH=$(readlink -f "$0")

But if you need a workaround to get the absolute path both in Linux and Mac then you can actually do this:

PATH_TO_SCRIPT=$(cd ${0%/*} && echo $PWD/${0##*/})
PATH_TO_FOLDER=`dirname "$abspath"`
TWO_LEVELS_UP=`cd "${PATH_TO_FOLDER}/../.." && pwd -P`