Have you ever had the problem that you want to run a script but because
it handles relative paths it depends on the directory it’s called from?
Well, today I learned about a shell function that helps with that, called dirname
.
It can be fed a path and will return it with the last non-slash component and trailing slash removed. So to refer to the location a script sits in you can do simply:
dirname "$0"
Here $0
expands to the full path of the script. Now you can save it to a variable:
SCRIPT_DIR=$(dirname "$0")
And from here on you can prefix any relative path with $SCRIPT_DIR
and the script will
behave the same, regardless of where it was called from.