Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtualenv activate script won't run in bash script with set -euo

I am trying to create a bash script that activates the virtualenv, pip installs the requirements.txt and continue. This will be my init.sh script for later business.

#!/usr/bin/env bash

set -euo pipefail

. ${DIR}/scripts-venv/bin/activate
pip install -r requirements.txt

where ${DIR} is set to my directory that contains the virtualenv. It seems the issue lies in the above set -euo which is the recommended start to bash scripts according to some style guides. More specifically, its the u option - interactive that gives the error /scripts-venv/bin/activate: line 57: PS1: unbound variable. I can remove it, but was just wondering why this is happening. Thanks

like image 235
AmaJayJB Avatar asked Mar 24 '17 10:03

AmaJayJB


1 Answers

If you can update, virtualenv>=16.2 no longer has errors from PS1 not being set

If you are able to update the virtualenv library you will find this is now fixed. It was fixed in pypa/virtualenv/pull/922, which was included in the 16.2 milestone.


Regarding versions < 16.2; and explanation of what you are seeing

$PS1 is the text that appears in front of the $ in your bash prompt. -u says that references to unbound variables are errors. Since /scripts-venv/bin/activate refers to $PS1 and since there's no prompt on an interactive shell then this is an unbound variable and -u causes the script to fail.

Maybe this helps:

https://unix.stackexchange.com/questions/170493/login-non-login-and-interactive-non-interactive-shells

When you call a script, the shell that runs that script doesn't have a prompt. Now, look inside bin/activate, line 57:

_OLD_VIRTUAL_PS1="$PS1" 

You can see that $PS1 is going to get evaluated, and because you have -u set, your script can't continue because -u says an attempt to do parameter evaluation of an unset variable is an error.

Here are some options for you:

Option 1: You could fix bin/activate

LINE 57:

-   _OLD_VIRTUAL_PS1="$PS1"  
+   _OLD_VIRTUAL_PS1="${PS1:-}" 

Line 61:

-        PS1="(`basename \"$VIRTUAL_ENV\"`) $PS1"
+        PS1="(`basename \"$VIRTUAL_ENV\"`) ${PS1:-}"

The :- syntax causes the expansion to default to an empty string instead of unbound so there's no error. But this is heavy handed because you're messing with the virtualenv created code.

Option 2: Workaround it

Probably its better just to remove -u during the activate script.

Try this script, to see what I mean:

#!/bin/bash

set -eux
echo "Testing vitualenv"
set +u
. venv/bin/activate
set -u
echo "Test complete $?"

By turning off -u during activate and then turning it back on again you can just work around the virtualenv awkwardness (if you don't want to fix it).


Option 3 [the future!]

Just update virtualenv so it is version >= 16.2. pip install --upgrade virtualenv

like image 200
JawguyChooser Avatar answered Sep 20 '22 15:09

JawguyChooser