Is there a command to go inside a bash .sh script that will provide the full path to the directory containing that script?


See the answers on Get the source directory of a Bash script from within the script itself. The accepted one recommends


DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

but reading all the answers gives a lot of alternatives (and insights into how shells work).

| improve this answer | |

The answers here do not always contain best practices, so if you just want the directory echoed on the screen (even when it contains spaces):

echo "My Script is being run from here: $(dirname "$0")"

If you want it into a variable and want . expanded to the full path, you need GNU Readlink first so:

  1. Install homebrew
  2. Install GNU CoreUtils:

    brew install coreutils
  3. Use the following script:

    szMyPath=$(dirname "$0")
    if [[ $szMyPath =~ ^. ]]; then 
      szMyPath="$(dirname "$(greadlink -f "$0")")" 
    echo "$szMyPath"
| improve this answer | |
  • The second, longer version is giving me an error: readlink: illegal option -- f. – murray Aug 24 '19 at 19:01
  • @murray Edited. My apologies for the error. – Fabby Aug 27 '19 at 7:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .