Run a Shell Script Auto-matically When Entering/cd a Directory
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:
1
|
|
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:
- Open your
~/.bash_profile
, and insert:
1 2 3 4 5 6 7 8 9 |
|
- And then source it in your terminal:
1
|
|
- Create new file named
.bash_local
under your target directories(on my machine, it is~/development/rails-dev/graduation-project/
), and then insert:
1
|
|
- Now cd the directory, and the alias
rspec_lib
will be available auto-matically:
1 2 3 4 5 6 7 8 |
|
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?