79425215

Date: 2025-02-09 16:13:10
Score: 0.5
Natty:
Report link

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)?

Reasons:
  • Blacklisted phrase (0.5): thanks
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • High reputation (-1):
Posted by: Doncho Gunchev