August 11, 2010, 7:32 PM — Ever type "rm -rf dirname" and then realize you've just blown away the wrong directory? You can always alias the rm command to "rm -i", but let's look at a way that you can selectively determine which directories get that special "Are you sure you want to do that?" treatment and which get quietly blown away.
The basis of this little trick is Unix file name expansion and the fact that the hyphen comes earlier in the ASCII character set than letters of the alphabet. You type an asterisk after the ls command and the shell expands it into a list of file names. If you create a file named "-i" in a particular directory, any "rm -rf" commands turn into "rm -rf -i" commands, forcing you into interactive mode. Create these files only in the directories that you don't want to be removed without verifying that you really know what you're doing and you've got a content-sensitive file removal scheme.
Then, when you're faced with the interactive file removal questions, you can either control-c your way back to safety or choose to remove your files interactively.
$ rm -rf * rm: examine files in directory d1_test1 (yes/no)? no rm: examine files in directory d1_test2 (yes/no)? yes rm: remove d1_test2/f1 (yes/no)? yes rm: remove d1_test2/f2 (yes/no)? no rm: remove d1_test2/f3 (yes/no)? yes
To create your -i files from directories you no longer want to safeguard, you will have to use the "--" (don't interpret remaining arguments as command options) trick. This touch command will not interpret "-i" as anything but a file name.
$ touch -- -i
Another way to do this is to include the current directory in your command. For example:
$ touch ./-i
Once you've created your -i file, even you use the force (-f) option, a subsequent interactive (-i) option takes precedence.
To remove the -i file from a directory, you would use a similar command:
$ rm -- -i
$ rm ./-i
If you want to protect a directory containing subdirectories, you should include a -i file in each subdirectory included within the directory. Otherwise, you lose the effect when you run your "rm -f" command in anything but the top level directory. To recursively protect your directories from absent minded destruction, you can do this:
$ cd targetdir $ for dir in `find .