egig egig - 8 months ago 35
Bash Question

Get current directory and concatenate a path

This is a shell script (.sh file). I need to create an absolute path based on the current directory. I know about

, but how do I concatenate it with another string? Here is an example of what I am trying to do:



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.