When committing Mathematica notebooks to GitHub, is there a way to automatically remove output cells (as some "filter")? I know that for Jupyter notebooks, there is a Python package nbstripout. I wish to find something similar to that for Mathematica.

  • 3
    $\begingroup$ In Mathematica, use the menu command Cell | Delete All Output $\endgroup$
    – Bob Hanlon
    Commented May 3, 2023 at 3:36
  • $\begingroup$ I know this, but hope to find something automatic. $\endgroup$ Commented May 4, 2023 at 4:04

1 Answer 1


Here is a rough solution you can start with.

Important and annoying issue is that you need to have those notebooks closed otherwise they are locked and can not be overwritten. This issue is so annoying that I don't know if I wouldn't go with different approach, like a shortcut in MMA to clean+save so that they are clean already. But I wanted to do this exercise anyway.


The script from the bottom of this post should be put in your repo .git/hooks/pre-commit.

I have an example with a single notebook:

$ git status
On branch master
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        modified:   test.nb

That contains Output cells

$ cat test.nb | grep Output
Cell[BoxData["6"], "Output",
Cell[842, 28, 173, 2, 32, "Output",ExpressionUUID->"0bf38f70-6261-4f5b-8c7f-c5c14b4f8d93"]

Let's commit:

$ git commit -m "test"
Notebooks output cleanup...
 - test.nb cleaned
[master 464d4da] test
 1 file changed, 10 insertions(+), 18 deletions(-)
$ git status
On branch master
nothing to commit, working tree clean
$ cat test.nb | grep Output

ToDo, if you want to

  • I tried it on Windows
  • output cell pattern is really basic, it could include other cells, e.g. those with GenerateCell->True option[*]
  • I scan for .nb in top working dir but change FileNames line to get what you want
  • it may be enough to scan only staged (add-ed) .nb-s, assuming others underwent the cleaning procedure earlier
  • I assumed that Import-DeleteCases-Export will be faster than spinning the front end, even if invisible, and using Delete Output tokens but I didn't test to confirm

[*] and in general but very rare cases it may be necessary to go through the custom stylesheet

pre-commit script

#!/usr/bin/env wolframscript

$outputCellPattern = Cell[_, ___, "Output", ___];

, nb = Import[nbPath]

; If[ FreeQ[nb, $outputCellPattern]
  , Print[" - ", nbPath, " already clean"]; Return["clean", Module] 

; nb = DeleteCases[ nb, $outputCellPattern, Infinity ]

; Check[ Export[ nbPath, nb ], Print[nbPath, " locked, aborting "]; Exit[1]]

; Print[" - ", nbPath, " cleaned"]
; Run["git add " <> nbPath]


Print["Notebooks output cleanup..."]

deleteOutputCells /@ FileNames["*.nb"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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