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


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?

  • What do you mean within emacs? What kind of environment variables are we talking about? Do you mean in an eshell (or other emacs shell) instance? What do the environment variables actually do?
    – terdon
    Oct 7, 2013 at 15:14

3 Answers 3


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.


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
  3. Exit subshell, return to vim. Then invoke another subshell (:sh).

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

If all you need is to unset LD_LIBRARY_PATH after loading Emacs, just add

(setenv "LD_LIBRARY_PATH")

to ~/.emacs or other init file.

If you need to swap back and forth, save the result of (getenv "LD_LIBRARY_PATH") in a variable first so you can restore it later.


I've found this nice piece of Emacs lisp that uses diff to compare outputs of export command before and after sourcing, and then calls setenv function accordingly: https://gist.github.com/ffevotte/9345586

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .