Search code examples
org-modeorg-babel

Get value of a variable from another session in org-mode


How to share variables' values in org-mode between different sessions?

Simple example: in session one I create _gpg_tmpdir

#+name: make_temporary_directories
#+begin_src bash :session *one*
_gpg_tmpdir="$( mktemp -d )"
#+end_src

and need to clean up it in session two:

#+name: clean_temporary_directories
#+begin_src bash :session *two*
rm -rf $_gpg_tmpdir
#+end_src

The example is for the demonstration purpose only. The question is what is the less painfull way to share variables between different code sessions (perhaps with different code languages) in org-mode.


Solution

  • You can use the name of the codeblock to reference its output from a different codeblock using the "var" attribute. For more info you can check in the orgmode documentation.

    The first block needs to output the value:

    #+name: make_temporary_directories
    #+BEGIN_SRC bash :session *one* :results output
    variable=`ls`
    echo $variable
    #+END_SRC
    
    #+RESULTS: make_temporary_directories
    : 
    : file1 file2 file3 file4 file5 file6 file7 file8
    

    The second block can refer to that value using the name of the previous codeblock:

    #+BEGIN_SRC bash :session *two* :results output :var ls_result=make_temporary_directories
    echo $ls_result
    #+END_SRC
    
    #+RESULTS:
    #+begin_example
    
    bash-5.0$ file1 file2 file3 file4 file5 file6 file7 file8
    #+end_example