Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bash script not sourcing

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 .profile or .bashrc
  • assumes your PATH has been configured so the OS can find poetry

Now instead of referencing the script you reference the function; an example of referencing the function from the command line:

$ poetry_activate
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading