Issue
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?
Solution
For the relative path (i.e. the direct equivalent of Windows' %~dp0
):
MY_PATH="$(dirname -- "${BASH_SOURCE[0]}")"
echo "$MY_PATH"
For the absolute, normalized path:
MY_PATH="$(dirname -- "${BASH_SOURCE[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"
Answered By - vladr Answer Checked By - Senaida (WPSolving Volunteer)