Run bash script on `cd` command
linux, python, ruby
Solution
One feature of Unix shells is that they let you create shell functions, which are much like functions in other languages; they are essentially named groups of commands. For example, you can write a function named `mycd` that first runs `cd`, and then runs other commands:
function mycd () {
cd "$@"
if ... ; then
workon environment
fi
}
(The `"$@"` expands to the arguments that you passed to `mycd`; so `mycd /path/to/dir` will call `cd /path/to/dir`.)
As a special case, a shell function actually supersedes a like-named builtin command; so if you name your function `cd`, it will be run instead of the `cd` builtin whenever you run `cd`. In that case, in order for the function to call the builtin `cd` to perform the actual directory-change (instead of calling itself, causing infinite recursion), it can use Bash's `builtin` builtin to call a specified builtin command. So:
function cd () {
builtin cd "$@" # perform the actual cd
if ... ; then
workon environment
fi
}
(Note: I don't know what your logic is for recognizing a project directory, so I left that as `...` for you to fill in. If you describe your logic in a comment, I'll edit accordingly.)
Problem
I'm python developer and most frequently I use buildout for managing my projects. In this case I dont ever need to run any command to activate my dependencies environment. However, sometime I use virtualenv when buildout is to complicated for this particular case. Recently I started playing with ruby. And noticed very useful feature. Enviourement is changing automatically when I `cd` in to the project folder. It is somehow related to `rvm` nad `.rvmrc` file. I'm just wondering if there are ways to hook some script on different bash commands. So than I can `workon environment_name` automatically when `cd` into to project folder. So the logic as simple as: When you `cd` in the project with `folder_name`, than script should run `workon folder_name`