I've been working on my Bash scripts and trying to implement a system for unique sourcing from a common file, `base.sh`, to reduce redundancy. Here's what I'm aiming for: if `A.sh` sources `base.sh` and `B.sh` also sources it (but indirectly through `A.sh`), I want `base.sh` to only be sourced once. I'm currently using a guard in `base.sh` that looks like this: `[ -n ${__BASE_sh__} ] && return || __BASE_sh=.` This seemed to work until I faced another issue where `foobar.sh`, which sources `base.sh`, fails when called from `main.sh`. After troubleshooting, I realized my checks for whether `__BASE_sh__` is set weren't handling quoting properly. I discovered that using `[ ! -z "${__BASE_sh__}" ]` is the correct approach. Additionally, I learned from a user that proper quoting is vital and using `[[ ... ]]` can avoid issues with word splitting and pathname expansion. I'm looking for any tips or alternative solutions for ensuring scripts are only sourced once effectively!
3 Answers
I had a similar challenge and solved it by using a guard variable at the top of each script. Something like `if [[ -v MY_GUARD_VAR ]]; then return; fi; MY_GUARD_VAR=1`. This avoids multiple inclusions safely. Additionally, I keep my common scripts in a folder and pull them in through a single entry point, which makes sourcing easier to manage and track.
The key issue with your original check was the lack of quoting. Using `[ -n "${__BASE_sh__}" ]` instead of `[ -n ${__BASE_sh__} ]` prevents unexpected behavior when the variable is empty. Also, using `[[ ... ]]` is definitely a better practice in Bash since it handles these cases more gracefully without splitting. However, for more robust solutions, consider using associative arrays to track sourced scripts, which can help you avoid sourcing problems even with complex interdependencies.
You might want to explore a loader pattern for your scripts. For instance, create a `loader.sh` that sources all required scripts. You can manage the load order and avoid naming conflicts there. This could help ensure that necessary initialization happens correctly without difficulties, especially with more complex setups.
Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically