Blog Tags: 

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:

    for script in $1/*; do

        # skip non-executable snippets
        [ -x "$script" ] || continue

        # execute $script in the context of the current shell
        . $script

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


  1. Modular: add or remove code without having to edit a big monolithic file.

  2. Order of execution is determined by the filename. Changing the order is as simple as changing a number prefix.

  3. 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!


curt smith's picture

I think Shell scripts allow several commands that would be entered manually at a command line interface to be executed automatically, and without having to wait for a user to trigger each stage of the sequence. For example, in a directory with three C source code files, rather than manually running the four commands required to build the final program from them, one could instead create a C shell script, here named build and kept in the directory with them, which would compile them automatically.



Liraz Siri's picture

Hi Kevin, thanks for sharing. I never thought to separate shell hooks by function/alias. What's your rational for doing that?


Add new comment