Shell [ARTICLE] Relative shell script includes with realpath on FreeBSD

I like writing shell scripts, but one thing that has bugged me for years is that I don't reliably know how to include relative scripts. I run into three key problems:
  1. . relative/script.sh depends on the invocation dir.
  2. Symlinking the command results in inconsistent command name and location.
  3. Almost all internet discussion about shell scripting is about Bash, whereas I'm using sh(1) on FreeBSD (aka Bourne shell).
tl;dr: The Solution

Use $(dirname $(realpath $0)) in your command files. realpath(1)

full article
 
This pattern has only been annoying for me on macos, which previously didn't include realpath, but now it does! So if you are up to date on macos, then this pattern should work reliably on linux/bsd/mac for your portable scripts.
 
Back
Top