kvz / bash3boilerplate

Templates to write better Bash scripts
http://bash3boilerplate.sh
MIT License
2.08k stars 196 forks source link

Resolve symlinks to find __origin #160

Open efelon opened 2 years ago

efelon commented 2 years ago

I propose another magic variable __origin which can be used for all dependencies. It would be the same as __dir except when called via symlink.

Context

I usually place bash scripts in /opt/myscript/myscript.sh and use aliases. But if they are of good use to other users I would like to create a symlink to /usr/local/bin/myscript. Here I noticed that __dir would give me the directory of the symlink rather the one from the origin /opt/myscript. One may or may not have some dependencies at the origin which would not be found.

I read some time about the usage of realpath vs readlink -f, where my conclusion for now is to stick with readlink.

Example

cd /opt && git clone https://github.com/kvz/bash3boilerplate.git LOG_LEVEL=7 /opt/bash3boilerplate/main.sh -f testp

2022-03-16 15:56:24 UTC [ info] __i_am_main_script: 1 2022-03-16 15:56:24 UTC [ info] file: /opt/bash3boilerplate/main.sh 2022-03-16 15:56:24 UTC [ info] dir: /opt/bash3boilerplate 2022-03-16 15:56:24 UTC [ info] __base: main

ln -s /opt/bash3boilerplate/main.sh /opt/run

LOG_LEVEL=7 /opt/run -f testp

Before the change

2022-03-16 15:53:40 UTC [ info] __i_am_main_script: 1 2022-03-16 15:53:40 UTC [ info] file: /opt/run 2022-03-16 15:53:40 UTC [ info] dir: /opt 2022-03-16 15:53:40 UTC [ info] __base: run

After the change

LOG_LEVEL=7 /opt/run -f testp

2022-03-16 16:47:40 UTC [ info] __i_am_main_script: 1 2022-03-16 16:47:41 UTC [ info] file: /opt/run 2022-03-16 16:47:41 UTC [ info] dir: /opt 2022-03-16 16:47:41 UTC [ info] base: run 2022-03-16 16:47:41 UTC [ info] `origin: /opt/bash3boilerplate`