Reputation: 6235
I want to write a small script to source my virtualenv (for a Python project) directory. When I am somewhere inside my project directory, I know that the "venv" directory for my virtual environment is in a directory that is one of the ancestors of my current directory.
I want to write a shell script that will source venv/bin/activate
and its effect should persist outside this shell script. This is not happening right now.
Here's my code:
#!/bin/bash
#set -x
while [ $PWD != "/" ]; do
#echo $PWD
if [ -d "venv" ]; then
echo "venv found in $PWD. Sourcing."
source venv/bin/activate
break
else
cd ..
fi
done
Why does it not work right now, and how can I fix it?
EDIT:
If it helps, the contents of venv/bin/activate are here: http://pastebin.com/TZ40brsq It is generated by the virtualenv tool (generally used with Python projects).
Upvotes: 3
Views: 3065
Reputation: 246744
You cannot affect your current environment by using a shell script that runs in a child process.
If you add pushd "$(pwd)"
before the while loop and popd
after, you can get what you want by sourcing the script file instead of executing it
Upvotes: 3
Reputation: 131550
You will have to invoke the script using
source path/to/script
or
. path/to/script
(same thing) rather than running it. It's a security measure that when you run a program, it cannot change the environment of its parent process (i.e. your shell session). However, when you use source
, you're telling the shell to read the contents of the file and run it as if you had typed that contents yourself.
If you're already sourcing the script in this way, then I'm not sure what's going on.
Upvotes: 4