3

I use an alias to prevent me from accidentally deleting files, and I would like to do something similar for directories.

For files, I have the following added to my .bashrc:

alias rm="rm -i"

I would like to also prevent myself from accidentally removing a directory, which I have tried by doing this:

alias rm -rf="rm -rfi"

and this:

alias "rm -rf"="rm -rfi"

But neither work. Any suggestions?

2
  • 4
    Best practice to avoid accidents is by training yourself and your habits, one day you could run into the system without guidance or friendly support and your habits will rule.
    – rook
    Commented Aug 9, 2013 at 9:36
  • I agree with rook's comment. Ever since accidentally hitting enter while typing in "rm -rf /var/" before finishing the path "www/magento/var/cache/*" I never type "rm" without verifying I am in the deepest directory possible to do what I want. Commented May 5, 2014 at 19:33

2 Answers 2

6

From bash(1):

ALIASES

[... ]The first word of each simple command, if unquoted, is checked to see if it has an alias[...] The characters [...] and any of the shell metacharacters or quoting characters listed above may not appear in an alias name.

So aliases can only be a single word without any quoting characters.

Using both -f and -i in a call to rm also doesn't make much sense because they are somewhat contradictory(rm(1)):

-f, --force ignore nonexistent files and arguments, never prompt

-i prompt before every removal

But here's the good thing - your alias to rm is actually used even when you're calling rm -r, because the first word - rm - has an alias - rm -i, so it gets replaced by that!

$ alias rm
bash: alias: rm: not found
$ alias rm='rm -i'
$ mkdir test
$ rm -r test
rm: remove directory ‘test’?

/edit: Raphael Ahrens also mentioned in the comments that using -f (force) is not neceessary to remove directories (as can be already seen in my example), -r (recursive) enough is alone:

-r, -R, --recursive remove directories and their contents recursively

0
1

Aliasing rm is dangerous. As soon as you're on a 'box that doesn't have those aliases set up you'll do some damage.

As far as "prevent myself from accidentally removing a directory" that's the purpose of the -r flag to begin with.

Please don't override commands like that, you never know what assumptions scripts are going to make. If you must, choose a name other than rm, otherwise change something in your workflow that prevents you from using rm -rf with disregard.

1
  • If you want to disregard my advice, then create a script that wraps around /usr/bin/rm save it to /wtf/rm and prepend /wtf to your PATH like export PATH=/wtf:$PATH Commented Aug 9, 2013 at 8:57

You must log in to answer this question.

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