Snippets and other bits

Export an environment variable to Emacs

Jul 26, 2021

Handy function to export environment variables to Emacs from the command line:

function export-emacs {
    if [ "$(emacsclient -e t)" != 't' ]; then
        return 1
    fi

    for name in "${@}"; do
        value=$(eval echo \"\${${name}//\\\"/\\\\042}\")
        emacsclient -e "(setenv \"${name}\" \"${value}\")" >/dev/null
    done
}

Use it like this:

export BLAH="Some value"
export-emacs BLAH

And in emacs:

(getenv "BLAH") ; => "Some value"

update: A very kind soul updated the function to handle quoting properly. Thanks, @pcrama!


← Back to root