Get current directory and concatenate a path

Sounds like you want:


The $( opens a subshell (and the ) closes it) where the contents are executed as a script so any outputs are put in that location in the string.

More useful often is getting the directory of the script that is running:

dot="$(cd "$(dirname "$0")"; pwd)"

That’s more useful because it resolves to the same path no matter where you are when you run the script:

> pwd
> ./my_project/

rather than:

> pwd
> ./my_project/
> cd my_project
> pwd
> ./

More complex but if you need the directory of the current script running if it has been executed through a symlink (common when installing scripts through homebrew for example) then you need to parse and follow the symlink:

if [[ "$OSTYPE" == *darwin* ]]; then

dot="$(cd "$(dirname "$([ -L "$0" ] && $READLINK_CMD -f "$0" || echo "$0")")"; pwd)"

More complex and more requirements for it to work (e.g. having a gnu compatible readlink installed) so I tend not to use it as much. Only when I’m certain I need it, like installing a command through homebrew.

Leave a Comment