简体   繁体   中英

Run bash script on `cd` command

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

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.)

I think you're looking for one of two things.

autoenv is a relatively simple tool that creates the relevant bash functions for you. It's essentially doing what ruakh suggested, but you can use it without having to know how the shell works.

virtualenvwrapper is full of tools that make it easier to build smarter versions of the bash functions—eg, switch to the venv even if you cd into one of its subdirectories instead of the base, or track venvs stored in git or hg , or … See the Tips and Tricks page.

The Cookbook for autoenv , shows some nifty ways ways to use the two together.

Just found in the description of virtualenvwraper this topic

It describes exactly what I need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM