Safe rm, rmdir, find -delete, truncate, and dd shadows that prevent
or interpose on irreversible command-line data loss. Includes small shims and
guidance for macOS, common Linux sudoers setups, and NixOS.
Features
- Moves files/directories to OS trash (XDG trash on Linux, Finder Trash on macOS).
- Moves verified-empty directories invoked through
rmdirto Trash too. - Deletes outright, without logging, anything strictly inside the system temp directory (
$TMPDIRand/tmp;RM_SAFE_TEMP_DIRS, colon-separated, replaces that list) or already in the Trash. Temporary files are disposable, and removing a Trash entry means it; its.trashinforecord goes with it. Directories still need-r, a symlink is removed without its target, and the check uses the real parent directory, so..and symlinked parents cannot move a path into or out of a zone. - Converts a restricted terminal
find -deleteexpression into safe Trash moves. - Requires explicit confirmation before
truncateshrinks an existing file. - Requires explicit confirmation before
ddwrites to an existingof=target. - Refuses to touch protected locations (
/,/etc,/nix/store, etc.). - Works with sudo via a wrapper, not shell aliases.
- Restores manual trash entries with
--undoor--undo-picker(gum or fzf). - Prints the Trash action log, newest first, with
--log, or only the newest N entries with--log=N. A plain--logrefuses a log of more than 10,000 entries (RM_SAFE_LOG_LIMITchanges the limit). - Built-in test suite:
bin/rm-safe --test.
rm-safe runs on a stock macOS or Linux box with nothing to install:
git clone https://github.com/pmarreck/rm-safe.git rm-safe
# put the shim + universal bash implementation on your PATH
ln -s "$PWD/rm-safe/bin/rm" ~/.local/bin/rm
ln -s "$PWD/rm-safe/bin/rmdir" ~/.local/bin/rmdir
ln -s "$PWD/rm-safe/bin/find" ~/.local/bin/find
ln -s "$PWD/rm-safe/bin/truncate" ~/.local/bin/truncate
ln -s "$PWD/rm-safe/bin/dd" ~/.local/bin/dd
ln -s "$PWD/rm-safe/bin/rm-safe.bash" ~/.local/bin/rm-safe.bashThat's the whole install. rm moves files to Trash, and rmdir moves empty
directories to Trash. Ordinary find searches pass through unchanged; the
accepted find -delete form moves matches to Trash. All work on the bash that
ships with macOS (3.2) and on Linux.
The truncate shadow leaves no-op and growing resizes alone. Before shrinking
an existing regular file, it reports each target's current and requested size
plus bytes to discard, then requires --confirm. It calculates absolute,
relative, reference, rounding, and I/O-block size forms; an unrecognized form
also requires confirmation and reports the limit of its forecast.
The dd shadow requires --confirm when of= names an existing regular,
special, or directory/mount target. Its refusal names the supplied and resolved
target when the host can resolve it, type, current regular-file size, input,
relevant operands, and an
exact transfer upper bound only when count and input block size are plain
decimal values. With no count, it reports that input is unbounded.
The rmdir shadow retains the non-recursive boundary: it rejects non-empty
directories, --parents/-p, and other rmdir-specific options it cannot carry
through a single safe trash operation. -v/--verbose and -- are supported.
The find shadow accepts exactly one terminal -delete action with ordinary
implicit-AND predicates, for example find . -type f -mtime +30 -delete. It
rejects Boolean operators, -prune, duplicate deletion actions, and any
non-terminal -delete because replacing a Boolean deletion predicate could
change the result of the original expression. It traverses depth-first, routes
files and symlinks to rm-safe, and routes real directories to the rmdir
shadow so unmatched children cannot be moved recursively. If it cannot
unambiguously parse a -delete expression, it refuses to run it rather than
guess whether -delete was an action or an argument.
To prevent one command shadow from selecting another as its real executable,
the shim resolves REAL_FIND, gfind, or a system find path. The package
sets REAL_FIND automatically. A nonstandard manual installation should set
REAL_FIND to the underlying executable; the shim refuses an unproved generic
PATH candidate rather than risk a wrapper loop.
- Speed: install luajit and the shim automatically uses the faster
bin/rm-safe. Any luajit will do — no LuaFileSystem or other Lua rocks needed, sincebin/rm-safereaches the filesystem through its own FFI shim. Without luajit you'll see a one-time note (silence it withRM_SAFE_QUIET=1). - Nix:
nix developfor a managed dev/test environment, ornix build .#rm-safe/.#rm-safe-bashfor packaged builds.
Set RM_SAFE_BIN=/path/to/rm-safe.bash (or the luajit bin/rm-safe) to force a
specific implementation for rm, rmdir, and the tests.
Files
bin/rm-safe.bash— universal bash implementation; works on macOS bash 3.2 and Linux with no extra dependencies.bin/rm-safe— faster LuaJIT implementation; used automatically when any luajit is available (no Lua rocks required).bin/rm— wrapper shim: dispatchesRM_SAFE_BINoverride → luajit → bash fallback; if neither safe implementation is available, it refuses the operation rather than call system rm. After moving files to the Trash it says so on stderr, naming them, so a script that expected deletion finds out.OBLITERATE=1 rm ARGS…passes the arguments to the system rm (REAL_RM, else/run/current-system/sw/bin/rmon NixOS, else/bin/rm) and refuses when that rm is missing or is the shim itself. GNU rm ignores the variable, so the same command still deletes where a Nix shell puts it first. Set it per command; exporting it disables the Trash for every later rm.bin/rmdir— wrapper shim: verifies directories are empty, then dispatches torm-safe -r; it refuses a system-rmdir fallback so a partial install cannot delete permanently.bin/find— wrapper shim: passes ordinary searches to real find; rewrites the accepted terminal-deleteform into NUL-delimited safe Trash moves and reports any failed deletion.bin/truncate— wrapper shim: forecasts shrinking existing regular files and requires--confirm; it then delegates unchanged to realtruncatewith that private switch removed.bin/dd— wrapper shim: forecasts writes to an existingof=target and requires--confirm; it then delegates unchanged to realddwith that private switch removed.bin/test/rm-safe_test— undo/restore tests.bin/test/rm_override_test— shim tests.bin/test/fs_shim_test— provesbin/rm-safeneeds no LuaFileSystem, and diffs its FFI filesystem shim against real lfs.bin/test/run-all— runs the full test suite across luajit / bash-4+ / bash-3.2 lanes.
Platform notes Why sudo setup differs by OS:
- macOS
sudopreserves the userPATHby default, so a user-level shim earlier inPATH(e.g.,~/bin/rm) will still be found under sudo. - Most Linux distros set
secure_pathin sudoers, which replaces the userPATHwith a fixed, root-owned path for safety. That means user-level shims are ignored unless you place a root-owned shim in the secure path.
macOS (defaults keep user PATH under sudo)
- Symlink or copy
bin/rm,bin/rmdir,bin/find,bin/truncate, andbin/ddinto~/bin(or any user directory already ahead of/binon PATH). sudo rm …,sudo rmdir …,sudo find … -delete,sudo truncate …, andsudo dd …will hit the shims because PATH is preserved by default.
Linux with sudo secure_path
- Create a root-owned override dir, e.g.
/usr/bin/overrides(0755, root:root). - Install the shims there as
rm,rmdir,find,truncate, anddd, and ensurerm-safeis reachable (the same dir is simplest). - In sudoers (via
visudo), prepend the override dir:Defaults secure_path="/usr/bin/overrides:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" - Avoid adding broad dirs like
/usr/local/binjust to get the shim; overrides keeps blast-radius small.
NixOS (declarative)
- Build/install
rm-safeand therm/rmdir/find/truncate/ddshims into a root-owned path on PATH, e.g./run/wrappers/bin. - Example snippet:
# configuration.nix { security.sudo.extraConfig = '' Defaults secure_path=/run/wrappers/bin:/usr/bin:/bin ''; environment.systemPackages = [ rm-safe-package ]; environment.pathsToLink = [ "/run/wrappers/bin" ]; } - Ensure
rmwrapper in that path execsrm-safe; shim already usescommand -p rmto reach the real rm when needed.
Claude Code / AI agent integration
-
Tools like
nix developprepend/nix/store/.../bintoPATH, shadowing user-levelrmshims with GNUrm. AI coding agents (Claude Code, Codex, etc.) run shell commands through these environments and can permanently delete files without realizing the safe wrapper is bypassed. -
To prevent this in Claude Code, add a global
PreToolUsehook that blocks barermin Bash calls:1. Create
~/.claude/hooks/block-rm/block-rm.sh:#!/bin/bash set -u COMMAND=$(jq -r '.tool_input.command') if echo "$COMMAND" | grep -qE '\brm\b' && ! echo "$COMMAND" | grep -qE 'rm-safe'; then echo "BLOCKED: Use rm-safe instead of rm." >&2 exit 2 fi exit 0
chmod +x ~/.claude/hooks/block-rm/block-rm.sh2. Add to
~/.claude/settings.jsonunderhooks.PreToolUse:{ "matcher": "Bash", "hooks": [ { "type": "command", "command": "~/.claude/hooks/block-rm/block-rm.sh", "timeout": 2 } ] }Any Bash tool call containing
rm(but notrm-safe) will be rejected before execution. The agent sees the block message and retries withrm-safe.
Concurrency
- Any number of
rm-safeprocesses may trash same-named items at once. A Trash name is reserved by creating its.trashinfowithO_CREAT|O_EXCL(the XDG Trash spec's protocol, shared with gio and trash-cli), and the item moves in with a no-replace rename (renameat2(RENAME_NOREPLACE)on Linux,renamex_np(RENAME_EXCL)on macOS), so an existing Trash entry is never overwritten. Cross-device items are first moved into a private staging directory inside the Trash, then renamed into place atomically. --undouses the same no-replace rename with no prior existence check, so a file or directory that appears at the original path (before or during the restore) is never replaced; the item stays in the Trash. Cross-device restores copy into a private staging directory beside the target, place the copy atomically, then delete the Trash original.- Log fragments and
.trashinfofiles are created exclusively (O_EXCL), and tools are invoked by resolved path, so exported shell functions (BASH_FUNC_cp%%etc.) cannot hijack them. - The bash fallback uses noclobber (
O_EXCL) for reservations and GNUmv -n -T(RENAME_NOREPLACE) for moves. Without GNUmvit usesln/ln -s(fail withEEXIST) for files and symlinks and plainmvfor directories, which cannot destroy data but can nest an item inside an empty directory that appears in the instant before the rename. The luajit implementation has no such gap.
Cautions
- Log-rotate/cleanup scripts that expect permanent deletion will move files to trash when the shim is first in PATH; the shim's stderr notice says so. Files in the system temp directory are deleted outright; elsewhere, scripts that intend permanent deletion can use
OBLITERATE=1 rm, or better, avoid files they must delete. - The
rmandrmdirshadows fail closed if no safe implementation is available. Repair the installation rather than expecting a system-command fallback. - The
rmdirshadow checks emptiness before moving a directory. Coordinate concurrent writers around that check; a filesystem cannot atomically test that a directory is empty and rename it into Trash. - The
findshadow rejects-deleteexpressions outside its documented subset before real find runs. A concurrent writer can still change a selected path between traversal and its safe move. - The
findshadow intentionally avoids a generic later-PATHfallback. SetREAL_FINDto the underlying binary when it is notgfindor in a standard system location. - The
truncateshadow samples file size before delegation. A concurrent writer can change a file between its forecast and the confirmed resize, so coordinate writers when exact byte preservation matters. - The
ddshadow cannot know the exact number of bytes a stream will yield or protect a target changed after its forecast. Its confirmation report labels exact bounds only when the operands prove them.
Testing
- Run all lanes (luajit / bash-4+ / bash-3.2):
bin/test/run-all - Shim:
bin/test/rm_override_test - Main tool:
bin/rm-safe --test - Undo/restore:
bin/test/rm-safe_test
License
- MIT (see LICENSE)