Last active
August 6, 2022 11:18
-
-
Save WieeRd/f82d91f451b459f877326d70949cd57a to your computer and use it in GitHub Desktop.
A wrapper around `rm` command to prevent disasters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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