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 Garnix

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 rmdir to Trash too.
  • Deletes outright, without logging, anything strictly inside the system temp directory ($TMPDIR and /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 .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 (/, /etc, /nix/store, etc.).
  • Works with sudo via a wrapper, not shell aliases.
  • Restores manual trash entries with --undo or --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 --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/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.bash

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

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. 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/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.
  • 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/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 — undo/restore tests.
  • bin/test/rm_override_test — shim tests.
  • 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/find, bin/truncate, and bin/dd into ~/bin (or any user directory already ahead of /bin on PATH).
  • sudo rm …, sudo rmdir …, 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, 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/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.

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; 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
  • Shim: bin/test/rm_override_test
  • Main tool: bin/rm-safe --test
  • Undo/restore: bin/test/rm-safe_test

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