Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activating a VirtualEnv using a shell script doesn't seem to work

I tried activating a VirtualEnv through a shell script like the one below but it doesn't seem to work,

#!/bin/sh source ~/.virtualenvs/pinax-env/bin/activate 

I get the following error

$ sh virtualenv_activate.sh  virtualenv_activate.sh: 2: source: not found 

but if I enter the same command on terminal it seems to work

$ source ~/.virtualenvs/pinax-env/bin/activate (pinax-env)gautam@Aspirebuntu:$ 

So I changed the shell script to

#!/bin/bash source ~/.virtualenvs/pinax-env/bin/activate 

as suggested and used

$ bash virtualenv_activate.sh  gautam@Aspirebuntu:$ 

to run the script .

That doesn't throw an error but neither does that activate the virtual env

So any suggestion on how to solve this problem ?

PS : I am using Ubuntu 11.04

like image 894
Gautam Avatar asked Sep 10 '11 02:09

Gautam


People also ask

How do I enable Virtualenv in bash?

venv/bin/activate manually it activates your virtual env as it can be seen in the terminal that . venv has been activated. But when you use the same command inside the bash script it does not activate . venv , seems that the command does not have any effect when running bash script.


1 Answers

TLDR

Must run the .sh script with source instead of the script solely

source your-script.sh 

and not your-script.sh

Details

sh is not the same as bash (although some systems simply link sh to bash, so running sh actually runs bash). You can think of sh as a watered down version of bash. One thing that bash has that sh does not is the "source" command. This is why you're getting that error... source runs fine in your bash shell. But when you start your script using sh, you run the script in an shell in a subprocess. Since that script is running in sh, "source" is not found.

The solution is to run the script in bash instead. Change the first line to...

#!/bin/bash 

Then run with...

./virtualenv_activate.sh 

...or...

/bin/bash virtualenv_activate.sh 

Edit:

If you want the activation of the virtualenv to change the shell that you call the script from, you need to use the "source" or "dot operator". This ensures that the script is run in the current shell (and therefore changes the current environment)...

source virtualenv_activate.sh 

...or...

. virtualenv_activate.sh 

As a side note, this is why virtualenv always says you need to use "source" to run it's activate script.  

like image 144
Mark Hildreth Avatar answered Oct 11 '22 15:10

Mark Hildreth