Determine the path of the executing BASH script

Bash

Bash Problem Overview


> Possible Duplicate:
> Can a Bash script tell what directory it's stored in?

In a Windows command script, one can determine the directory path of the currently executing script using %~dp0. For example:

@echo Running from %~dp0

What would be the equivalent in a BASH script?

Bash Solutions


Solution 1 - Bash

For the relative path (i.e. the direct equivalent of Windows' %~dp0):

MY_PATH=$(dirname "$0")
echo "$MY_PATH"

For the absolute, normalized path:

MY_PATH=$(dirname "$0")            # relative
MY_PATH=$(cd "$MY_PATH" && pwd)    # absolutized and normalized
if [[ -z "$MY_PATH" ]] ; then
  # error; for some reason, the path is not accessible
  # to the script (e.g. permissions re-evaled after suid)
  exit 1  # fail
fi
echo "$MY_PATH"

Solution 2 - Bash

Assuming you type in the full path to the bash script, use $0 and dirname, e.g.:

#!/bin/bash
echo "$0"
dirname "$0"

Example output:

$ /a/b/c/myScript.bash
/a/b/c/myScript.bash
/a/b/c

If necessary, append the results of the $PWD variable to a relative path.

EDIT: Added quotation marks to handle space characters.

Solution 3 - Bash

Contributed by Stephane CHAZELAS on c.u.s. Assuming POSIX shell:

prg=$0
if [ ! -e "$prg" ]; then
  case $prg in
    (*/*) exit 1;;
    (*) prg=$(command -v -- "$prg") || exit;;
  esac
fi
dir=$(
  cd -P -- "$(dirname -- "$prg")" && pwd -P
) || exit
prg=$dir/$(basename -- "$prg") || exit 

printf '%s\n' "$prg"

Solution 4 - Bash

Vlad's code is overquoted. Should be:

MY_PATH=`dirname "$0"`
MY_PATH=`( cd "$MY_PATH" && pwd )`

Solution 5 - Bash

echo Running from `dirname $0`

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAtif AzizView Question on Stackoverflow
Solution 1 - BashvladrView Answer on Stackoverflow
Solution 2 - BashAlex ReynoldsView Answer on Stackoverflow
Solution 3 - BashDimitre RadoulovView Answer on Stackoverflow
Solution 4 - BashPoor YorickView Answer on Stackoverflow
Solution 5 - BashxagygView Answer on Stackoverflow