Cannot activate virtual environment with a shell script
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. [ ... ]
Related videos on Youtube
Heuyie
Updated on September 18, 2022Comments
-
Heuyie over 1 year
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.
-
Heuyie over 6 yearsIt worked. I added the command I used. Thanks!
-
swateek almost 4 yearsA full implementation looks like this: digitalocean.com/community/questions/…