Safe rm, rmdir, unlink, 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. unlink FILEfollows the same rules asrm(it runs thermshim installed beside it), while keeping unlink(1)'s limits: exactly one operand, never a directory, no options.- Deletes outright, without logging, anything strictly inside the system temp directory (
$TMPDIR,/tmp, and on macOSDARWIN_USER_TEMP_DIR;RM_SAFE_TEMP_DIRS, colon-separated, replaces that list) or already in the Trash (its entries and their records, not the Trash's ownfiles/,info/and log directories). 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 and immutable files. Protected are
/and its top-level directories, everything under/etc,/usr,/var,/opt,/root,/bin,/sbin,/liband/nix/store(and macOS's/System,/Library,/private/etcand/private/var), and the Trash's ownfiles/,info/and log directories. Entries inside/var/cache,/var/logand/var/tmp(and their/private/varforms) are routine maintenance areas and go to the Trash like anything else; those directories themselves stay protected. A protected path moves to the Trash only when confirmed at a terminal;-fnever overrides protection or immutability, it only stops prompts, and its refusal names the two ways forward: confirm at a terminal, or delete permanently withOBLITERATE=1 rm. A refusal exits non-zero, so a caller can tell the path was not removed; declining an-iquestion exits 0, as in GNU rm. Without a terminal, every confirmation answers no. (RM_SAFE_SYSTEM_ROOT, for tests, applies the system patterns under a fixture directory as well; it only adds protection.) - Accepts GNU rm's
--one-file-systemand--preserve-root[=all], which scripts written for coreutils pass./is never removed, even with-f.--preserve-root=allrefuses an operand that is a mount point, and--one-file-systemrefuses a directory that has another file system mounted inside it; where GNU rm would skip just that subtree, rm-safe leaves the whole operand alone and exits non-zero. Both read the mount table (/proc/mounts, ormounton macOS) and refuse when it cannot be read.--no-preserve-rootand unknown options are refused by name. - Works with sudo via a wrapper, not shell aliases.
- Restores manual trash entries with
--undoor--undo-picker(gum or fzf). - Empties the Trash on macOS and Linux with
empty-trash, so nobody has tormit (see Emptying the Trash). - 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/unlink" ~/.local/bin/unlink
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/empty-trash" ~/.local/bin/empty-trash
ln -s "$PWD/rm-safe/bin/rm-safe.bash" ~/.local/bin/rm-safe.bashThat's the whole install. rm and unlink move 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. The system directories are
/run/current-system/sw/bin, /usr/bin and /bin;
RM_SAFE_SYSTEM_BIN_DIRS (colon-separated) replaces that list for the find
and rmdir shadows.
empty-trash permanently deletes what is in your Trash, on macOS and Linux
alike, so that nobody has to point rm at it:
empty-trash --dry-run # list what would go, with sizes
empty-trash --older-than=30 # only entries trashed more than 30 days ago
empty-trash # asks at a terminal; --yes skips the questionIt covers the home Trash (the XDG Trash on Linux, ~/.Trash on macOS) and your
own Trash on each mounted volume (.Trash-UID, a sticky .Trash/UID, and
macOS .Trashes/UID). --older-than uses each entry's .trashinfo
DeletionDate, else the time the entry last changed (a move into the Trash sets
it). Every target is written to rm-safe's Trash log, shown by rm-safe --log,
before anything is deleted, and nothing is deleted if that log cannot be
written. It never follows a symlinked Trash or Trash subdirectory, removes a
symlink entry without its target, keeps rm-safe's own log directory, refuses
an unknown platform, and without a terminal refuses unless given --yes.
Agents: use empty-trash rather than rm to reclaim Trash space, but only
when the owner asks. It deletes permanently, so ask first.
- 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. It reports on stderr what actually happened, one line per outcome, naming at most three operands and then "and N more": what it moved to the Trash (rm override: moved to the Trash instead of deleting: …), so a script that expected deletion finds out, and what it deleted outright (rm override: deleted permanently (inside a temp directory): …or(already in the Trash): …). Errors keep their usual messages,-fon a missing file prints nothing, and callingrm-safedirectly prints no report.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, including inside scripts started under it. Each honored call prints a one-line warning on stderr naming the system rm, so a leftover setting shows up on its first deletion.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/unlink— wrapper shim: checks unlink(1)'s limits (one operand, not a directory, no options), then runs thermshim installed beside it, which it recognizes by its header; without that shim it refuses rather than 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— log, undo/restore and picker tests.bin/test/rm-safe_zones_test— outright deletion (temp directories, entries already in a Trash) and the stderr notice.bin/test/rm-safe_cli_test— argument handling and exit status: refusals exit non-zero, terminal declines, GNU long options.bin/test/rm-safe_atomicity_test— concurrent, occupied-name and cross-device Trash placement/restore.bin/test/rm_override_test— rm shim tests;find_shim_test,resize_shim_testandunlink_shim_testcover the rmdir/find, truncate/dd and unlink shadows.bin/empty-trash— permanently empties the home and volume Trashes (see Emptying the Trash);bin/test/empty-trash_testchecks it against disposable fixtures only, never the real Trash.bin/test/impl-suitesandbin/test/shim-suitesrun every suite that sourcesrm_safe_test_lib.bashorshim_test_lib.bash.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/unlink,bin/find,bin/truncate, andbin/ddinto~/bin(or any user directory already ahead of/binon PATH). Keepunlinkin the same directory asrm. sudo rm …,sudo rmdir …,sudo unlink …,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,unlink,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/unlink/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.A finer hook can let plain
rmthrough whentype -P rmresolves to this shim. Recognize it by content:bin/rmand the wrapper the Nix package installs asrmare#!scripts whose first kilobyte contains the line# rm override shim:(the test suite and the package's install check keep it there). The shim's stderr report then tells the agent what eachrmdid: moved to the Trash, or deleted outright and why.
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, and the notice says that too; 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. The bash 3.2 lane runsrm-safe.bashand every shim under bash 3.2, as macOS/bin/bashwould. macOS supplies that bash; elsewhere the flake builds GNU bash 3.2.57 (nix build .#bash32), which the Nix check and devShell name inRM_SAFE_BASH32and a plain run builds itself. Without a bash 3.2 the lane fails rather than skips. - Shims:
bin/test/rm_override_test,find_shim_test,resize_shim_test(all:bin/test/shim-suites) - Main tool:
bin/rm-safe --test - Undo/restore, outright deletion and arguments:
bin/test/rm-safe_test,bin/test/rm-safe_zones_test,bin/test/rm-safe_cli_test,bin/test/rm-safe_atomicity_test(all:bin/test/impl-suites)
License
- MIT (see LICENSE)