Ray's Knowledge Base
Unlock

In a Jupyter notebook, ! lines get Python variables but a %%bash cell body does not

FactVerified 2 Oct 2026Holds anywhere
Fact. A statement and the evidence for it.

Statement#

How values go between Python and bash in IPython:

  • !echo {nodes} and !echo $nodes fill in the Python variable. A name Python does not know, such as $HOME, goes to the shell.
  • out = !cmd gives an SList of lines. out[0] is the first line and out.s is one string.
  • A %%bash cell body gets no Python values, so {nodes} stays as text. Pass a value with %%bash -s "$nodes" and read $1, or set %env NODES=$nodes (or os.environ) first.
  • A shell variable set in one %%bash cell is gone in the next cell. !export X=1 and !cd dir are also lost. Use %env and %cd.
  • %%bash --out name stores stdout in name as one string with the final newline.
  • A %%bash cell that exits non-zero raises CalledProcessError. A failed ! line raises nothing.
  • %%writefile f writes the cell body as-is, with no expansion.
  • ! runs the user's login shell (zsh on this Mac), so globs and quotes can differ from bash. %%bash is always bash.

Build and test a notebook from a MyST text file: uv run --with jupytext --with nbconvert --with ipykernel jupytext --from md:myst --to ipynb --execute lesson.md uv run --with pytest --with nbmake --with ipykernel pytest --nbmake lesson.ipynb A cell tagged raises-exception (:tags: [raises-exception]) may fail without failing the test.

Evidence#

Ran each case on 2026-10-02 through IPython.testing.globalipapp.start_ipython() with uv run --with ipython --with pytest python t.py. Without --with pytest the import fails with ModuleNotFoundError: No module named 'pytest'. The jupytext and nbmake commands ran on a four-cell sample and gave 1 passed.

Also found by searching

  • how do I pass a python variable into a %%bash cell
  • variable set in one bash cell is empty in the next notebook cell
  • CalledProcessError from %%bash cell
  • run and test a notebook from a markdown file with uv