9

I have to activate the virtual environment (venv) so I running these commands manually in terminal:

source .venv/bin/activate # To activate the virtual env.

and

deactivate # To deactivate the virtual env

This works fine when running manually. Now I have to insert these commands in a bash script to make AWS CodeDeploy to deploy it on a Ubuntu 18.04 server.

My bash script named after_install.sh looks like this...

#!/usr/bin/env bash

set -e source .venv/bin/activate

DO SOME STUFF

deactivate

For local testing, I made the script executable and ran the script using bash after_install.sh. But nothing happened. It doesn't activate the virtual environment. It seems none of the above commands worked while running the bash script.

I am not getting why these commands work when I run them manually but not with a bash script. What is going on? I need to write these commands inside the bash script so that AWS CodeDeploy can deploy it on the server.

7ochem
  • 162

5 Answers5

5

source file_name.sh

worked for me as well (as per Dipanwita Mallick's answer).

The full explanation for why this works is provided here by Lesmana. In summary:

  • Sourcing a script will run the commands in the current shell process. Changes to the environment take effect in the current shell.
  • Executing a script will run the commands in a new shell process.
2

Try to use the full path to virtualenv directory.

#!/usr/bin/env bash

set -e
source /full-path/to/.venv/bin/activate
## DO SOME STUFF -> USE FULL PATH HERE TOO #
deactivate

Best regards.

2

You can do the following using && to chain the commands and continue the lines using \:

#!/usr/bin/env bash

set -e source .venv/bin/activate &&
echo "DO SOME STUFF" &&
deactivate

kyrlon
  • 181
0

Use source to run the shell script.

source file_name.sh

It worked for me.

0

in addition to "activate" file I see python file in .my_env/bin/ so just writing .sh file with one line

./my_env/bin/python start.py

works fine. this python is from the env and it can see all required dependencies.