Prevent user typing accidental space between rm and wildcard

Intention:

rm -rf string*

Problem:

rm -rf string *

The first case is a legitimate and common use of rm, a small typo can cause a lot of problems in the second case. Is there a simple way to smartly protect against an accidental trailing or leading wildcard?


A DEBUG trap could be written to cancel commands that look suspicious. The following, or code similar to it, can be added to your ~/.bashrc:

shopt -s extdebug
checkcommand() {
  if [[ $BASH_COMMAND = 'rm -r'*' *' ]]; then
    echo "Suppressing rm -r command ending in a wildcard" >&2
    return 1
  fi
  # check for other commands here, if you like
  return 0
}
trap checkcommand DEBUG

Adjust the logic to taste.

(I don't actually expect this approach to be useful -- too many ways to mess up a command destructively to find them testing one-by-one -- but it provides a literal answer to the question).


There is no way to a totally bulletproof a system. And adding "Are you sure?" prompts to things is both counterproductive and leads to "Of course I'm sure." kneejerk reactions.

A trick I picked up from a book in years past is to first do ls -R blah* then, do rm -fr blah* if and only if the listing that ls turned up hit what I wanted hit.

It's easy enough to do the ls command first, then , delete the ls -R and replace with rm -fr.

The final question is, "If the information was valuable to you, where's your backup?"


Can you train yourself to use, say, rmrf in place of rm -rf?

If so, this bash function will provide you a chance to see what would actually happen before confirming the command:

rmrf() { echo rm -rf "$@"; read -p "Proceed (y/N)? "; [ "${REPLY,,}" = y ] && rm -rf "$@"; }

To make this function permanent, add this line to the ~/.bashrc file on each computer you use.

Comparison with the common rm alias

It is common to define an alias:

alias rm='rm -i'

This has two limitations:

  1. If you come to depend on this alias, then you will in for a shock when you are on a machine or in an environment that does not have it. By contrast, trying to run rmrf on a machine without that function will return a harmless command not found.

  2. This alias is no help in your case because the -f option that you supply on the command line overrides the -i option in the alias.