Skip to content

Instantly share code, notes, and snippets.

@ashleve
Created July 13, 2022 13:07
Show Gist options
  • Save ashleve/4f60a5f398eed16899defd1429aad00a to your computer and use it in GitHub Desktop.
Save ashleve/4f60a5f398eed16899defd1429aad00a to your computer and use it in GitHub Desktop.

Automatic activation of virtual environment and tab completion when entering folder

  1. Create a new file called .autoenv (this name is excluded from version control in .gitignore).
    You can use it to automatically execute shell commands when entering folder. Add some commands to your .autoenv file, like in the example below:

    # activate conda environment
    conda activate myenv
    
    # activate hydra tab completion for bash
    eval "$(python train.py -sc install=bash)"

    (these commands will be executed whenever you're openning or switching terminal to folder containing .autoenv file)

  2. To setup this automation for bash, execute the following line (it will append your .bashrc file):

    echo "autoenv() { if [ -x .autoenv ]; then source .autoenv ; echo '.autoenv executed' ; fi } ; cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv" >> ~/.bashrc
  3. Lastly add execution previliges to your .autoenv file:

    chmod +x .autoenv
    

    (for safety, only .autoenv with previligies will be executed)

Explanation

The mentioned line appends your .bashrc file with 2 commands:

  1. autoenv() { if [ -x .autoenv ]; then source .autoenv ; echo '.autoenv executed' ; fi } - this declares the autoenv() function, which executes .autoenv file if it exists in current work dir and has execution previligies
  2. cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv - this extends behaviour of cd command, to make it execute autoenv() function each time you change folder in terminal or open new terminal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment