Let me offer a solution that works even if the bash script ends with new line and the directory it resides in also does.
src=$(readlink -f -- "${BASH_SOURCE[0]}"; echo -n .); src="${src%??}"; src=$(dirname "$src"; echo -n .); src="${src%??}"; cd "$src"
or more verbose
src=$(readlink -f -- "${BASH_SOURCE[0]}" && echo -n .)
src="${src%??}"
src=$(dirname "$src" && echo -n .)
src="${src%??}"
cd "$src"
The echo -n .
ensures the new lines do not get stripped by the command substitution "$(…)"
. The src="${src%??}"
removes that extra dot and the last new line, which will be added by both readlink
and dirname
, thus leaving only the real path, even with new lines at the end.
Many thanks to everyone else who pointed out the use of "${BASH_SOURCE[0]}"
instead of "$0"
. Are there any corner cases I am missing here (except readlink
and dirname
not being available)?