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 $nodesfill in the Python variable. A name Python does not know, such as$HOME, goes to the shell.out = !cmdgives anSListof lines.out[0]is the first line andout.sis one string.- A
%%bashcell 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(oros.environ) first. - A shell variable set in one
%%bashcell is gone in the next cell.!export X=1and!cd dirare also lost. Use%envand%cd. %%bash --out namestores stdout innameas one string with the final newline.- A
%%bashcell that exits non-zero raisesCalledProcessError. A failed!line raises nothing. %%writefile fwrites 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.%%bashis 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