Run a shell script auto-matically when entering/cd a directory

May 2014 · 2 minute read

I don’t know if it is common that you need to run some shell scripts which are used under only some directories, such as, one of your Rails projects.

Today I find that I always need to run rspec command with a SPEC option, which specifies spec files to be run. In short, everytime I should type the following command in my terminal:

rake spec SPEC=spec/lib/

It is convenient to run this command as an alias, but I don’t want to write this alias into the ~/.bash_profile, because it should be available under the current directory only. But how?

Thanks to the powerful bash shell and its function, we can rewrite the built-in cd command through a function named cd. The following are steps:

  1. Open your ~/.bash_profile, and insert:

    function cd {
    # actually change the directory with all args passed to the function
    builtin cd "$@"
    # if there's a regular file named ".bash_local"...
    if [ -f ".bash_local" ] ; then
        # source its contents
        source .bash_local
    fi
    }
  2. And then source it in your terminal:

    $ source ~/.bash_profile
  3. Create new file named .bash_local under your target directories(on my machine, it is ~/development/rails-dev/graduation-project/), and then insert:

    alias rspec_lib='rake spec SPEC=spec/lib/'
  4. Now cd the directory, and the alias rspec_lib will be available auto-matically: ``` sh $ cd ~/development/rails-dev/graduation-project/ $ rspec_lib => …..

Finished in 0.00617 seconds 5 examples, 0 failures

Randomized with seed 23543 ```

Tips

Please consider if it is necessary to check .bash_local into your git repo. If not, remember to add it to the .gitignore file.

TODO

When leave the directory, how to “un-source” the sourced file, that is, make rspec_lib unavailable?

  1. How do you run a shell command/script automatically when entering/cd-ing a directory on Snow Leopard?
  2. Is it possible to “unsource” in bash?