Shell – Sourcing a shell script from within Emacs

emacsshellshell-script

I would like to source a shell script that changes my environment variables from within Emacs. That is, I would like the shell script to change the environment in which Emacs runs, and I would like to do this from within a running Emacs session.

In other words:

  1. I start Emacs from zsh
  2. I would like to source a zsh script from within Emacs that changes environment variables such as LD_LIBRARY_PATH

Background:

This is an attempt to circumvent the problem that I described here, where I need to set LD_LIBRARY_PATH to run Emacs, but I need to unset it to run a specific Python distribution (Anaconda).

Specifically, I want to use an Emacs package (emacs-jedi) that requires access to this Python distribution, but currently I need to unset LD_LIBRARY_PATH first to start Emacs, so I would need to set it later so that I can use emacs-jedi from within Emacs.

Is this at all possible?

Best Answer

I don't believe this is possible, since each time you're invoking a subshell to source the script you're invoking a child process from the original process where the emacs applications was launched.

The exporting of environment variables is a one way street where only the parent can provide variables to any child processes, but no child processes can manipulate the parent's environment.

Experiment

I'm using vim but the same should apply to emacs. Sample file to source.

$ more ~/vars.bash 
export VAR=somevalue
  1. Initial Parent environment, $VAR is unset

    $ echo $VAR
    
    $
    
  2. Launch vim. Then invoke a subshell to source the above file (:sh).

    # check variable
    $ echo $VAR
    
    $
    
    # source and re-check
    $ source ~/vars.bash
    $ echo $VAR
    somevalue
    
  3. Exit subshell, return to vim. Then invoke another subshell (:sh).

    $ exit
    
    ... back in vim, do another `:sh` ...
    
    # check variable
    $ echo $VAR
    
    $ 
    
Related Question