I would like a reliable way of getting the name of the directory where a script lives. I would like this approach to also work when called from the same directory (most use cases involving dirname $0 would return "." in this case). Here is one such approach:

FULL="$( cd "$(dirname "$0")" ; pwd -P )"

The logic is simple enough... move to the directory of the script, call pwd from there, and then strip away everything except the final directory name. However, I can't seem to figure out the syntax to convert this to a one-liner. I would like help doing that.


One approach is to use basename instead of your parameter substitution.

FULL=$(basename "$(cd $(dirname $0) ; pwd -P)")

The quotes are there to deal with directory names with spaces.
There must be a more elegant way to handle this, but this quick and dirty approach does what you need with a small modification to your current command.

Another method would be to rely on the PWD variable:

FULL=$(cd $(dirname $0) ; echo ${PWD##*/})

A method that does not require changing directory would rely on the readlink command:

FULL=$(basename "$(readlink -f $(dirname $0))")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.