I am trying to write a function that will interpolate the enviroment variables stored in process-environment in a string. For example, if I have the string "This is $Foo and ${Bar}_none and '$skip'" and process-environment containing '("Foo=off" "Bar=rab" "skip=piks") I would expect the resulting string to be "This is off and rab_none and 'piks'". However none of the options I have tried seem to respect the caller environment. I have tried

(shell-command-to-string (concat "echo -n " string))


(let ((env process-environment))
    (with-current-buffer standard-output
      (let ((process-environment env))
        (call-process-shell-command (concat "echo -n " string) nil t)))))

but neither of those work (they interpolate, but they don't use process-enviroment). Is there a way to accomplish this?


I think you're looking for the function substitute-env-vars:

substitute-env-vars is a compiled Lisp function in ‘env.el’.

(substitute-env-vars STRING &optional WHEN-UNDEFINED)

Substitute environment variables referred to in STRING.
‘$FOO’ where FOO is an environment variable name means to substitute
the value of that variable.  The variable name should be terminated
with a character not a letter, digit or underscore; otherwise, enclose
the entire variable name in braces.  For instance, in ‘ab$cd-x’,
‘$cd’ is treated as an environment variable.

If WHEN-DEFINED is nil, references to undefined environment variables
are replaced by the empty string; if it is a function, the function is called
with the variable name as argument and should return the text with which
to replace it or nil to leave it unchanged.
If it is non-nil and not a function, references to undefined variables are
left unchanged.

Use ‘$$’ to insert a single dollar sign.

Here it is in action:

(let ((process-environment '("Foo=off" "Bar=rab" "skip=piks")))
  (substitute-env-vars "This is $Foo and ${Bar}_none and '$skip'"))

which gives

"This is off and rab_none and 'piks'"
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.