5

This question already has an answer here:

I read similar questions and have tried their suggestions but I still cannot activate my virtual environment. The hierarchy of directories is:

myproject
-- virtualenv
-- startvenv.sh

startvenv.sh is:

#!/bin/bash
source virtualenv/bin/activate

And, I am running startvenv.sh by:

./startvenv.sh

No error, but nothing happens. Why? Ideally, I want to open a new terminal and activate my virtual environment there.

marked as duplicate by muru bash Oct 17 '17 at 6:05

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

5

The virtualenv activates by sourcing (not normally running) the virtualenv/bin/activate script. If you want to do this in your own script, then you must source that script too and not just run it. Meaning:

source startvenv.sh

The difference between running and sourcing is that running executes the script in its own separate subshell, which is isolated from the parent shell (the one from which you called it) so that e.g. environment variables and other changes inside the script do not get propagated to the parent.

Sourcing explicitly does exactly that, executing the script in your current shell, which leaves all changes to environment variables etc intact after it finishes.

Here's a shorted extract from man bash (section about Shell Builtins):

    .  filename [arguments]
   source filename [arguments]
          Read and execute commands from filename  in  the  current  shell
          environment  and return the exit status of the last command exe‐
          cuted from filename.  [ ... ]
  • It worked. I added the command I used. Thanks! – Heuyie Oct 16 '17 at 23:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.