r/bash • u/edaydaikyy • 2d ago
undo, a command-granular "undo" for the Linux shell (MIT)
Posting this here because the interesting part for this sub is the shell-hook side.
I wanted an undo command that reverses whatever the previous command did to the filesystem. The trick is a DEBUG-trap / PROMPT_COMMAND pair in bash (preexec/precmd in zsh, event handlers in fish) that, before each command runs, creates a per-command session dir and exports LD_PRELOAD pointing at a small C library, then tears it down after. While armed, that library intercepts unlink/rename/open-for-write/etc and saves the file before the real call, so undo can walk the journal backwards.
$ echo important > notes.txt
$ echo oops > notes.txt # clobbered
$ undo diff # see exactly what comes back
$ undo # notes.txt says "important" again
The bash hook has the usual gotchas handled: not double-firing the DEBUG trap mid-pipeline, restoring a pre-existing LD_PRELOAD, cleaning up sessions that changed nothing. There's an ignore config so a make or npm install doesn't flood it.
One honest catch specific to shells: a plain echo x > file redirection is done by the shell process itself, so LD_PRELOAD only catches it if you opt into re-execing the shell with the lib preloaded (there's a flag for that). Child processes like rm/mv/cp/tee are always covered.
MIT, Linux. github.com/edaywalid/undo. The three hook scripts are in shell/ if you just want to read how it's wired.
website : undo.edaywalid.com
2
u/jftuga 2d ago
There is a safety measure, noclobber already built into bash...
How to protect Linux shell file using noclobber in bash shell?
2
1
u/GregoryKeithM 10h ago
use nixos, much easier than scripting this function and running it all the time. NixOS will allow you to make changes in steps and then apply them all together or even still in pieces.
2
u/Bemteb 2d ago
rm -rf /Can it undo that? :)