0

I am trying to write a simple script that will help me activate (source) the virtualenv and set some environment variables at the same time. Below is the current version that does not yet have any environment variables.

#!/bin/bash

if [ -z "$BASH_VERSION" ]
then
    exec bash "$0" "$@"
fi

# Your script here
script_dir=`dirname $0`
cd $script_dir
/bin/bash -c ". ./django-env/bin/activate; exec /bin/bash -i"

The trouble with this script is two-fold.

  1. When I run it - seemingly successfully as it changes the command line prefix to (django-env) - it is missing the My-Computer-Name: in front of it. Obviously, it is an indication of something as I typically have (django-env) My-Computer-Name: as the prefix.

  2. It does not activate the virtualenv properly. Namely, when I check which python, I am notified that the virtualenv Python is used. On the other hand, when I check for which pip or which python3, the global system's Python is used.

What can I do to fix these things and have the environment be activated?

5
  • 2
    Don't run in a sub-shell - remove /bin/bash -c, either straight . ./django-env/... or source ./django-env/... How are you running the script? Commented Aug 12, 2017 at 22:21
  • I was running source script.sh. Commented Aug 12, 2017 at 22:31
  • It looks like you're trying to reinvent the wheel - try virtualenvwrapper. Commented Aug 13, 2017 at 1:03
  • Does it give tools to work with environment variables? That is what I am doing. The task in question is just a quick aside. Commented Aug 13, 2017 at 1:57
  • There are hooks for all operations (creation, activation etc.) so you can manipulate env vars from there (hooks are basically bash scripts). Commented Aug 13, 2017 at 11:01

2 Answers 2

2

I suspect the problem with exec /bin/bash -i — the executed bash could run .bash_profile and .bashrc that change the current environment.

Instead of a shell script that executes shells upon shells you better create an alias or a shell function:

django_activate() {
    cd $1
    . ./django-env/bin/activate
}

Put it in .bashrc so it will be available in all shells and run as django_activate $venv_dir; for example django_activate ~/projects/work.

Sign up to request clarification or add additional context in comments.

Comments

0

The following code does what I intended it to do. I run it with source script.sh

#!/bin/bash

if [ -z "$BASH_VERSION" ]
then
    exec bash "$0" "$@"
fi

# Your script here
script_dir=`dirname $0`
cd $script_dir
/bin/bash -c ". ./django-env/bin/activate"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.