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?
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?
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"
$BASH_SOURCE. From this post.$(dirname $(readlink $0)) seems to work$0 does not work when the script is run using source script or . script; the name of the script is not available.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.
$BASH_SOURCE. From this post.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"
$PATH search; however, the above is NOT POSIX. It will only work with bash. Use which instead of command and backticks instead of $(...) is this has to run under other, older shells.ksh etc., not just bash, will run the above, but quite a few people out there are still on Solaris 10 (end-of-support is 2018, quite a few more years to go), and some even run old AIX and HP-UX.Vlad's code is overquoted. Should be:
MY_PATH=`dirname "$0"`
MY_PATH=`( cd "$MY_PATH" && pwd )`