Skip to content
pmarreckPublic

About

Prevent yourself from getting burned by `rm -rf`/`sudo rm -rf` style mistakes by diverting those files to the Trash instead.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

rm-safe

CI Mechatron Prime CI

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 rmdir to Trash too.
  • unlink FILE follows the same rules as rm (it runs the rm shim 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 macOS DARWIN_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 own files/, info/ and log directories). Temporary files are disposable, and removing a Trash entry means it; its .trashinfo record 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 -delete expression into safe Trash moves.
  • Requires explicit confirmation before truncate shrinks an existing file.
  • Requires explicit confirmation before dd writes to an existing of= 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, /lib and /nix/store (and macOS's /System, /Library, /private/etc and /private/var), and the Trash's own files/, info/ and log directories. Entries inside /var/cache, /var/log and /var/tmp (and their /private/var forms) 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; -f never overrides protection or immutability, it only stops prompts, and its refusal names the two ways forward: confirm at a terminal, or delete permanently with OBLITERATE=1 rm. A refusal exits non-zero, so a caller can tell the path was not removed; declining an -i question 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-system and --preserve-root[=all], which scripts written for coreutils pass. / is never removed, even with -f. --preserve-root=all refuses an operand that is a mount point, and --one-file-system refuses 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, or mount on macOS) and refuse when it cannot be read. --no-preserve-root and unknown options are refused by name.
  • Works with sudo via a wrapper, not shell aliases.
  • Restores manual trash entries with --undo or --undo-picker (gum or fzf).
  • Empties the Trash on macOS and Linux with empty-trash, so nobody has to rm it (see Emptying the Trash).
  • Prints the Trash action log, newest first, with --log, or only the newest N entries with --log=N. A plain --log refuses a log of more than 10,000 entries (RM_SAFE_LOG_LIMIT changes the limit).
  • Built-in test suite: bin/rm-safe --test.

Quick install (no dependencies)

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.bash

That'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.

Emptying the Trash

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 question

It 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.

Optional upgrades

  • Speed: install luajit and the shim automatically uses the faster bin/rm-safe. Any luajit will do — no LuaFileSystem or other Lua rocks needed, since bin/rm-safe reaches the filesystem through its own FFI shim. Without luajit you'll see a one-time note (silence it with RM_SAFE_QUIET=1).
  • Nix: nix develop for a managed dev/test environment, or nix build .#rm-safe / .#rm-safe-bash for packaged builds.

Choosing an implementation

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: dispatches RM_SAFE_BIN override → 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, -f on a missing file prints nothing, and calling rm-safe directly prints no report. OBLITERATE=1 rm ARGS… passes the arguments to the system rm (REAL_RM, else /run/current-system/sw/bin/rm on 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 to rm-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 the rm shim 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 -delete form 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 real truncate with that private switch removed.
  • bin/dd — wrapper shim: forecasts writes to an existing of= target and requires --confirm; it then delegates unchanged to real dd with 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_test and unlink_shim_test cover 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_test checks it against disposable fixtures only, never the real Trash.
  • bin/test/impl-suites and bin/test/shim-suites run every suite that sources rm_safe_test_lib.bash or shim_test_lib.bash.
  • bin/test/fs_shim_test — proves bin/rm-safe needs 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 sudo preserves the user PATH by default, so a user-level shim earlier in PATH (e.g., ~/bin/rm) will still be found under sudo.
  • Most Linux distros set secure_path in sudoers, which replaces the user PATH with 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, and bin/dd into ~/bin (or any user directory already ahead of /bin on PATH). Keep unlink in the same directory as rm.
  • sudo rm …, sudo rmdir …, sudo unlink …, sudo find … -delete, sudo truncate …, and sudo 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, and dd, and ensure rm-safe is 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/bin just to get the shim; overrides keeps blast-radius small.

NixOS (declarative)

  • Build/install rm-safe and the rm/rmdir/unlink/find/truncate/dd shims 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 rm wrapper in that path execs rm-safe; shim already uses command -p rm to reach the real rm when needed.

Claude Code / AI agent integration

  • Tools like nix develop prepend /nix/store/.../bin to PATH, shadowing user-level rm shims with GNU rm. 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 PreToolUse hook that blocks bare rm in 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.sh
    

    2. Add to ~/.claude/settings.json under hooks.PreToolUse:

    {
      "matcher": "Bash",
      "hooks": [
        {
          "type": "command",
          "command": "~/.claude/hooks/block-rm/block-rm.sh",
          "timeout": 2
        }
      ]
    }

    Any Bash tool call containing rm (but not rm-safe) will be rejected before execution. The agent sees the block message and retries with rm-safe.

    A finer hook can let plain rm through when type -P rm resolves to this shim. Recognize it by content: bin/rm and the wrapper the Nix package installs as rm are #! 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 each rm did: moved to the Trash, or deleted outright and why.

Concurrency

  • Any number of rm-safe processes may trash same-named items at once. A Trash name is reserved by creating its .trashinfo with O_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.
  • --undo uses 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 .trashinfo files 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 GNU mv -n -T (RENAME_NOREPLACE) for moves. Without GNU mv it uses ln/ln -s (fail with EEXIST) for files and symlinks and plain mv for 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 rm and rmdir shadows fail closed if no safe implementation is available. Repair the installation rather than expecting a system-command fallback.
  • The rmdir shadow 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 find shadow rejects -delete expressions outside its documented subset before real find runs. A concurrent writer can still change a selected path between traversal and its safe move.
  • The find shadow intentionally avoids a generic later-PATH fallback. Set REAL_FIND to the underlying binary when it is not gfind or in a standard system location.
  • The truncate shadow 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 dd shadow 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 runs rm-safe.bash and every shim under bash 3.2, as macOS /bin/bash would. macOS supplies that bash; elsewhere the flake builds GNU bash 3.2.57 (nix build .#bash32), which the Nix check and devShell name in RM_SAFE_BASH32 and 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)

About

Prevent yourself from getting burned by `rm -rf`/`sudo rm -rf` style mistakes by diverting those files to the Trash instead.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages