Shortcut for fast recursive removal

command linefiles

Sometimes I want to delete large swaths of temporary files recursively, and recycle the directory name without waiting for the command to complete. (For example, if I want to nuke and re-checkout a version control working copy.)

While this doesn't happen all that often, when it does I usually use a command like:

mv "$oldname" dienow && rm -rf dienow &

I could create a function or alias for this, of course, but without doing that is there a shorter way to express the above?

Best Answer

I would stick with two separate commands:

mv "$oldname" dienow
rm -rf dienow

This way, if you accidentally recall a line from your history, you don't risk causing major damage by running a single command. The mv command doesn't delete "$oldname" even if it's the new version, and the rm command only deletes something that you've already declared as to-be-deleted.

If you feel lucky and insist on a single command, make it a function:

mv_then_rm () {
  mv -- "$1" "$1.TO_BE_DELETED" && rm -rf -- "$1.TO_BE_DELETED" &
}

Here's a multi-parameter version that ensures the “to be deleted” directory doesn't exist yet.

mv_then_rm () {
  local d tmpdir tmpdirs
  tmpdirs=()
  for d; do
    tmpdir=$(mktemp -- "$(dirname -- "$d")/.deleting.XXXXXXXXXX")
    tmpdirs+=$tmpdir
    mv -- "$d" "$tmpdir"
  done
  rm -rf -- "$tmpdirs" &
}
Related Question