6

I have a BASH script in org-mode file as org-babel source block. I hope to pass value contains environment variable to it through :var.

something like these:

#+begin_src sh :var VAR1="~/foo"
  mkdir ${VAR1}/test

and

#+begin_src sh :var VAR1="${MY_ENV_VAR}/foo"
  mkdir ${VAR1}/test

When I run the code block with C-c C-c, they all complain about can't find that ${VAR1} directory.

I think inside the bash shell, ${VAR1} is not expended proper.

What's the right way to do it?

  • Try #+begin_src sh :var VAR1=(substitute-in-file-name "$MY_ENV_VAR/foo"). – Tobias Jun 22 '15 at 8:06
  • @Tobias Thanks for your reply. I tried you solution. It works environment variable, such as, ${HOME}, but still doesn't work with ~. – Enze Chi Jun 23 '15 at 12:09
  • 2
    Try #+begin_src sh :var VAR1=(expand-file-name (substitute-in-file-name "$MY_ENV_VAR/foo")). This is ugly, I have to admit. – Tobias Jun 23 '15 at 12:16
2

First Thanks @Tobias for the answer which solved my problem. But after more test, I just found that still has small issue about the solution if use expand-file-name.

For example, if your environment variable is just string instead of real file name or directory (like ${USER}), the expand-file-name would add some directory before that and that may not what your want. So you have to know what's the variable would look like before you code it.

To solve this problem, I just write a simple function which only apply expand-file-name if the result of subsitute-in-file-name start with ~.

Function:

(defun ec-expand-env (str)
  "Expand the environment variables in the STR."
  (let ((expanded-str (substitute-in-file-name str)))
    (if (string-prefix-p "~" expanded-str)
        (expand-file-name expanded-str)
      expanded-str)
    )
  )

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.