In my folder where I keep my other bash scripts, I have created this one:
#! /bin/bash
source $(poetry env info --path)/bin/activate
In a file named poetry_activate. In a bash terminal, the autocomplete works, and when I enter poetry_activate, the virtual environment is not loaded…
However, if I do source $(poetry env info --path)/bin/activate in the terminal, it works. It also works if I do . poetry_activate…
Is there a way to just make the script poetry_activate work?
>Solution :
When you execute the script you initiate a subshell; variable assignments made in the subshell are ‘lost’ when the subshell exits (in this case the poetry_activate script exits).
As you’ve found, when you source the script (. poetry_activate or source poetry_activate) then no subshell is initiated and instead the commands (within the script) are executed within the current shell.
To eliminate the subshell, while also removing the need to source the script, you could replace the shell script with a function, eg:
poetry_activate() { source $(poetry env info --path)/bin/activate; }
# or
poetry_activate() {
source $(poetry env info --path)/bin/activate
}
NOTES:
- in the first example the trailing
;is required to separate the code from the closing} - add this to your
.profileor.bashrc - assumes your
PATHhas been configured so the OS can findpoetry
Now instead of referencing the script you reference the function; an example of referencing the function from the command line:
$ poetry_activate