A few times I have accidentally executed the command sudo rm -rf /.

Is there a way how to prevent me from running this command? For example can I somehow disable it using the sudoers file?

  • 2
    How do you accidentally type this command and then execute it?? – fnord_ix Jun 19 '15 at 1:12
  • If I type in a command like this. sudo rm -rf / Applications/chess.app Notice the space between the / and the A. That's how – iProgram Jun 19 '15 at 9:43

You can add a line like

%admin ALL = !/bin/rm -rf /

to your sudoers file to prevent the execution of the command with the specific options.

Or, if you want to exclude several commands, you can work with command aliases

Cmnd_Alias DANGEROUS_CMNDS=/bin/rm -rf /, /bin/rm -fr /

You can also try to play it safe by using

Cmnd_Alias DANGEROUS_CMNDS=/bin/rm -rf /, /bin/rm -fr /, /bin/rm / *, /bin/rm * /, /bin/rm -rf / *, /bin/rm -rf * /, /bin/rm -fr / *, /bin/rm -fr* /

but there still might be other ways you can shoot yourself in the foot with rm so be careful anyway.

But keep in mind that all matching is done on the full string of the command, so sudo rm -rf /Volumes would still work (as would cd /; sudo rm -rf .).

PS: By all means, use sudo visudo to edit the sudoers file and NEVER edit it directly

PPS: I obviously didn't test this with rm (only with /bin/echo instead)

  • Comments are not for extended discussion; this conversation has been moved to chat. – bmike Jun 16 '15 at 19:46

I know you phrased the question in a way that makes me suspect you don't want to hear this answer, but you really should remove yourself from the sudoers file if you're prone to making the same mistake over and over.

The underlying problem is you haven't aliased rm to be move to trash (which is clearly how you are using it currently and in the past) or otherwise forced rm -r to be forced into rm -ri

alias rm='/bin/rm -i'

You can always get around the alias with command rm -rf whatever once you've trained your mind on when measure twice, cut once is needed for rm -rf use.

  • Thanks for that tip. I was thinking on making am hidden admin account (to access terminal only) and a standard account for normal use only. I could make the wrapper to move to the trash instead too. Thanks for that tip. I think that preventing sudo may be a safer step. I will still make sure I can access it by logging into the hidden admin. – iProgram Jun 17 '15 at 6:47
  • Haven't marked is a s answered though since it doesn't answer the above. This is still good advice though – iProgram Jun 17 '15 at 6:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .