Run the bash script at the `cd` command line.

I am a python developer and most often use buildout to manage my projects. In this case, I do not need to run any command to activate the dependency environment.

However, sometimes I use virtualenv when the assembly is complicated for this particular case.

I recently started playing with a ruby. And I noticed a very useful feature. Enviurement automatically changes when I cd is in the project folder. This has something to do with the rvm nad .rvmrc .

I'm just wondering if there are ways to connect some script to various bash commands. So that I can workon environment_name automatically when cd in the project folder.

So the logic is simple:

When you cd in a project with folder_name , than the script should run workon folder_name

+4
source share
3 answers

One of the features of Unix shells is that they allow you to create shell functions that are very similar to functions in other languages; they are essentially called team groups. For example, you can write a function called mycd that first runs cd and then runs other commands:

 function mycd () { cd " $@ " if ... ; then workon environment fi } 

( " $@ " expands to the arguments you passed to mycd , so mycd /path/to/dir will call cd /path/to/dir .)

As a special case, the shell function actually supersedes the built-in command with a similar name; therefore, if you name your function cd , it will run instead of the built-in cd every time you run cd . In this case, in order for the function to call the built-in cd to actually change the directory (instead of calling itself, causing infinite recursion), it can use the built-in Bash builtin to call the specified built-in 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 it as ... for filling. If you describe your logic in a comment, I will edit it accordingly.)

+10
source

I think you are looking for one of two things.

autoenv is a relatively simple tool that creates the appropriate bash functions for you. Essentially, this is what ruach suggested, but you can use it without knowing how the shell works.

virtualenvwrapper full of tools that make it easier to build smarter versions of bash functions, like switching to venv even if you cd into one of your subdirectories instead of the base or tracks stored in git or hg , or ... See Tips and Tricks .

A cookbook for autoenv , shows some useful ways to use these two.

+2
source

Just found in virtualenvwraper's description of this section

He accurately describes what I need.

0
source

Source: https://habr.com/ru/post/1491158/


All Articles