Ominus
Ominus

Reputation: 5721

VirtualEnv initilaized from a bash script

I am trying to write what should be a super simple bash script. Basically activate a virtual env and than change to the working directory. A task i do a lot and condesing to one command just made sense.

Basically ...

#!/bin/bash
source /usr/local/turbogears/pps_beta/bin/activate
cd /usr/local/turbogears/pps_beta/src

However when it runs it just dumps back to the shell and i am still in the directory i ran the script from and the environment isn't activated.

Upvotes: 8

Views: 6333

Answers (4)

MusikPolice
MusikPolice

Reputation: 1759

I know that I'm late to the game here, but may I suggest using virtualenvwrapper? It provides a nice bash hook that appears to do exactly what you want.

Check out this tutorial: http://blog.fruiapps.com/2012/06/An-introductory-tutorial-to-python-virtualenv-and-virtualenvwrapper

Upvotes: 0

eusid
eusid

Reputation: 769

I imagine you wish your script to be dynamic, however, as a quick fix when working on a new system I create an alias.

begin i.e

the env is called 'py1' located at ~/envs/py1/ with a repository location at ~/proj/py1/

alias py1='source ~/envs/py1/bin/activate; cd ~/proj/py1/;

end i.e

You can now access your project and virtualenv by typing py1 from anywhere in the CLI.

I know that this is no where near ideal, violates DRY, and many other programming concepts. It is just a quick and dirty way of getting your env and project accessible quickly without having to setup the variables.

Upvotes: 1

tripleee
tripleee

Reputation: 189297

The value of cd is local to the current script, which ends when you fall off the end of the file.

What you are trying to do is not "super simple" because you want to override this behavior.

Look at exec for replacing the current process with the process of your choice.

For feeding commands into an interactive Bash, look at the --rcfile option.

Upvotes: 1

Nicola Musatti
Nicola Musatti

Reputation: 18218

All you need to do is to run your script with the source command. This is because the cd command is local to the shell that runs it. When you run a script directly, a new shell is executed which terminates when it reaches the script's end of file. By using the source command you tell the shell to directly execute the script's instructions.

Upvotes: 21

Related Questions