1

I am trying to put a source command in a bash script so that I can quickly set up and use a virtual environment when writing django websites.

I tried the following without much success as my path was not prefixed with the (path) like it does when I simply enter it at the prompt.

#!/bin/bash
current=$(pwd | cut -d'/' -f5)
source ~/Documents/virtual-env/$current/bin/activate

Can anybody help and let me know what I am overlooking?

EDIT:

pwd is "example" and the source is:
"~/Documents/virtual-env/example/bin/activate".

After some research I think I need to use something like:
"source ./script"

(not working) as I think the environment is created but not esculated to its parent enviroment which I believe is not possible now.

phuclv
  • 37,963
  • 15
  • 156
  • 475
Stephen Brown
  • 564
  • 1
  • 9
  • 23
  • What is the output of `pwd` from within the script, and what would be the corresponding path that you are trying to source? Show at least one example. – Tom Fenech Sep 28 '17 at 10:07
  • pwd is "example" and the source is "~/Documents/virtual-env/example/bin/activate". After some research I think I need to use something like "source ./script" (not working) as I think the environment is created but not esculated to its parent enviroment which I believe is not possible now. – Stephen Brown Sep 28 '17 at 10:18
  • 2
    Yeah you can't change the parent environment by running a script (which happens in a child process), you need to source it. But it's still unclear exactly what you're trying to do. – Tom Fenech Sep 28 '17 at 10:55
  • Note that you need to source your script for the same reason *it* needs to source, not execute, the `activate` script. – chepner Sep 28 '17 at 11:00
  • What does "without much success" mean, exactly? Did you get an error? What are the exact paths involved? It's very difficult to diagnose when we have such limited information. – ghoti Sep 28 '17 at 12:56
  • I am trying to produce scripts for creating virtual environments and turning them off and on. Idealy I would like to create a directory "mkdir example" move into it "cd example" and then create an environment at "~/Documents/virtual-env/example" from reading the name of the directory I am in. Which I have managed but then some script to activated it as I am tired of typing "source ~/Documents/virtual-env/example/bin/activate" – Stephen Brown Sep 28 '17 at 13:07

1 Answers1

1
#!/bin/bash
current=$(basename $(pwd))
source ~/Documents/virtual-env/$current/bin/activate
exec bash # Run new interactive shell in the new environment

But I recommend to try virtualenvwarpper instead.

phd
  • 82,685
  • 13
  • 120
  • 165