DEV Community

Juan Burgos
Juan Burgos

Posted on

Micro-Post: Stop using `rm` to delete things!

The rm shell command is probably the most dangerous command in popular use. You can accidentally delete things you never meant to delete. As such, there are several precautions one should take to avoid any horrific situations.

The following are some simple things you can set in your shell's configuration files (i.e. .bashrc, .zshrc, etc.) that should come in handy!

(1) Always adding -i to request confirmation before deletion and -v to see exactly what you are deleting, like so:

alias rm='rm -i -v'
Enter fullscreen mode Exit fullscreen mode

Note that this approach may still fail if you add -f which forces the deletion operation, so be aware that, though useful, this strategy is not a panacea.

(2) Avoiding use of rm completely and switching to a custom soft-delete method as shown below:

function softdelete() {
  local -r path=$(realpath -q "${1}")
  [[ -z "${1}" || -z "${path}" ]] && {
    echo "No valid path was found for argument '${1}'"
    return 1
  }
  local -r backup ="/tmp/$(echo -n "${path}" | tr /' '_')"
  mv -v ${path} ${backup}
}
Enter fullscreen mode Exit fullscreen mode

Note that this approach is less versatile since you don't have all the command-line options rm provides. However, the benefits should far outweigh the costs since this method effectively soft-deletes files/folders alike to the /tmp directory. Though you could always modify this to point to any other directory of your choosing.

Another benefit of this method is that it preserves the original file path with /'s replaced with _'s so you don't have to remember the file's original path. This also helps with filename collisions to some extent.

Hope others find this useful!

Top comments (1)

Collapse
 
pengshp profile image
Neal

You can try rip.Rm ImProved (rip) is a command-line deletion tool focused on safety, ergonomics, and performance. Use it as a safer alternative to rm.