If you have a long-running emacs session it is sometimes convenient to change or set the values of the UNIX “environment” variables of the emacs process. This is easy to do using the “setenv” function.

For example, you may have a long-term sessions running within screen terminal simulator, but at some point you also log in to the machine with a X-windows session and wish for your emacs to launch graphical programs into that session. You can do that by setting the DISPLAY environment variable::

(setenv "DISPLAY" ":0")

(Alternatively you can set an environment variable by typing M-x setenv and filling out the prompts.) This will not of course change this emacs session into the graphical X11 version, but will any subprograms run by emacs from this session can be X11 based. Typical usage would be to launch document viewers from the dired mode.

Other possible uses:

  • Setting the PATH

  • Setting SSH_AGENT_PID if you have a new agent running

  • Setting environment variables that are used by compilers, configure scripts, etc.

Sometimes you may wish to add to an existing environment variable instead of overwriting. For example, you may wish to add to the PATH variable. This can be easily done using a combination of setenv, getenv and concat::

(setenv "PATH" (concat "/home/an_user/bin:"
    	    (getenv "PATH")))


  1. You can execute arbitrary elisp commands by writing them in the scratch buffer and pressing the C-M-x key combination after the closing parenthesis of the command that you wish to execute.
  2. You can also execute emacs lisp one-liners by pressing the M-: key (normally this is in fact the M-Shift-; combination, since : is shift-; ).
  3. Added 15th August 2020. If you find yourself modifying PYTHONPATH, you should probably consider ```pyvenv`` package and using virtual environments.

“Path from shell” package

Added 15th August 2020. There is also a useful package exec-path-from-shell (which is install-able from MELPA) which starts a new user shell and picks up some environment variables from there.