This is a very basic question, and surely has been asked before, but I am having trouble finding the answer or guidance. There are e.g. these but they don't quite hit the mark:

Essentially I just want to remove a temporary directory tree as part of a bash script, like so

rm -rf $my_path

But I'm a bit paranoid that somewhere else in the script it could be possible for $my_path to expand out into / or something equally bad. For example if somewhere there is my_path=$var1/$var2 and both $var1 and $var2 end up defaulting to empty strings or some such.

What is the best practice way to write this kind of command into a script to avoid accidental enormous problems?

  • Validate $var1 and $var2 at the points they are defined. If $myvar is critical then validate it when it's defined. There are only so many ways you can protect an rm (is it / or $HOME, etc) but you should consider what else has already expected it to have a meaningful value Jul 15, 2021 at 6:38
  • rm --preserve-root=all -Ir -- "$my_path"
    – alecxs
    Jul 15, 2021 at 18:31


You must log in to answer this question.

Browse other questions tagged .