egig egig - 6 months ago 25
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

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

"$pwd/some/path"

Answer

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.