Home > Mobile >  Bash script to run commands if in directory
Bash script to run commands if in directory

Time:08-13

Goal: Automatically execute bash commands if when in directory.

For example, if I enter a git project directory, I'd like bash to run the following for me:

  • conda activate
  • export VAR_NAME=foo

I attempted by appending to ~/.bashrc, but with no luck:

...
if [ -f "/home/me/PycharmProjects/project/" ]; then
    conda activate project_venv
    export KEY=foo
    export SECRET=bar
fi

Implementing Solution

~/.bashrc:

# ...
cd () {
    command cd "$@" &&
    if [[ $(pwd) = '/home/me/PycharmProjects/project1' ]]; then
        conda activate project1
        ~/miniconda3/etc/activate.d/env_vars.sh
    elif [[ $(pwd) = '/home/me/PycharmProjects/project2' ]]; then
        conda activate project2
    else
        ~/miniconda3/etc/deactivate.d/env_vars.sh
    fi
}

Activating of conda environments works!

However, exports aren't working.

~/miniconda3/etc/activate.d/env_vars.sh:

#!/bin/sh

export KEY=foo
export SECRET=bar

~/miniconda3/etc/deactivate.d/env_vars.sh:

#!/bin/sh

unset KEY
unset SECRET

I ran:

chmod 777 ~/miniconda3/etc/activate.d/env_vars.sh
chmod 777 ~/miniconda3/etc/deactivate.d/env_vars.sh

When I run code in any project, I get:

decouple.UndefinedValueError: KEY not found. Declare it as envvar or define a default value.

CodePudding user response:

You can add this function to your ~/.bashrc:

cd () { 
    command cd "$@" &&
    if [[ $(pwd) = '/home/me/PycharmProjects/project' ]]; then
        conda activate project_venv
        export KEY=foo SECRET=bar
    fi
}

CodePudding user response:

You can set PROMPT_COMMAND, see the bash docs. Bash executes its value (or if it's an array, each of its values) before every prompt, so you can do whatever you want when PWD changes.

CodePudding user response:

Because you are exporting in a function you need to use declare -gx declare --help will give you the best and most accurate reason why but it is because all function vars are technically local. The -g create a global exported var for a function is ignored if not in a function and the -x is what export is an alias for. export is just declare -x. You will also need to source your script files

So it will look like this

declare -gx KEY=foo
declare -gx SECRET=bar
cd () {
    command cd "$@" &&
    if [[ $(pwd) = '/home/me/PycharmProjects/project1' ]]; then
        conda activate project1
        source ~/miniconda3/etc/activate.d/env_vars.sh
    elif [[ $(pwd) = '/home/me/PycharmProjects/project2' ]]; then
        conda activate project2
    else
       source ~/miniconda3/etc/deactivate.d/env_vars.sh
    fi
}

Full disclosure I'm not sure if the -x is completely necessary but I do it in case of sourcing a script.

Also storing in secrets in ~/.bashrc is a general no no as it leads to bad actors getting secrets. Ontop of slowing down your interactive shell loading times

  • Related