You are here
Smack yourself if you don't use generic shell script hooks
Smack yourself in the forehead if you don't use the following snippet (or an equivalent) in all custom shell scripts that could benefit from a hooking mechanism:
run_scripts()
{
for script in $1/*; do
# skip non-executable snippets
[ -x "$script" ] || continue
# execute $script in the context of the current shell
. $script
done
}
run_scripts path/to/hooks.d
I've found this pattern useful in nearly every sufficiently complex shell script I maintain, and I even use it to help manage my bashrc and xsession configurations:
$ ls .bashrc.d/
paths git editor pager autologout qemu tmpdirs scratch
$ ls .xsession.d/
10-lang 10-tmpdir 90-bell 90-kbdrate 91-xscreensaver 99-fvwm-conf
Features:
-
Modular: add or remove code without having to edit a big monolithic file.
-
Order of execution is determined by the filename. Changing the order is as simple as changing a number prefix.
-
Disable execution by removing execution bit:
chmod -x .bashrc.d/git
These days breaking down configurations into separate modular files like this is common in the Linux world, so by now I expect many experienced users are wondering why I'm channeling Captain Obvious. Just keep in mind that many Linux newbies haven't yet learned all our best practices and some lessons are worth reteaching.
Why not share your own tricks? Post a comment!