Skip to content

Instantly share code, notes, and snippets.

@WieeRd
Last active August 6, 2022 11:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WieeRd/f82d91f451b459f877326d70949cd57a to your computer and use it in GitHub Desktop.
Save WieeRd/f82d91f451b459f877326d70949cd57a to your computer and use it in GitHub Desktop.
A wrapper around `rm` command to prevent disasters
#!/usr/bin/env python3
"""
A wrapper around `rm` command to prevent disasters.
1. Put this script inside `~/.local/bin` (or anywhere on your system)
2. Enable the executable permission of the script using `$ chmod u+x safe-rm.py`
3. Add `alias rm=~/.local/bin/safe-rm.py` in your `~/.bashrc`
4. When removing 3+ files, confirm prompt with a list of targets to be removed will show up
"""
import subprocess
import sys
import click
import pprint
def main():
# list of arguments without `-` prefix (not an option)
args = [arg for arg in sys.argv[1:] if not arg.startswith("-")]
# confirm prompt when removing more then 3
if len(args) >= 3:
print(f"You're about to remove:")
pprint.pprint(args, indent=1)
click.confirm("Do you want to continue?", default=True, abort=True)
# run `rm` with same arguments
result = subprocess.run(
["rm", *sys.argv[1:]],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
print(result.stdout.decode())
if __name__ == "__main__":
try:
main()
except click.Abort:
print("Aborted")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment