Get current directory and concatenate a path

Sounds like you want:

path="$(pwd)/some/path"

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)"
path="$dot/some/path"

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

> pwd
~
> ./my_project/my_script.sh
~/my_project/some/path

rather than:

> pwd
~
> ./my_project/my_script.sh
~/some/path
> cd my_project
> pwd
~/my_project
> ./my_script.sh
~/my_project/some/path

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
  READLINK_CMD='greadlink'
else
  READLINK_CMD='readlink'
fi

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