(#18110) Don't do recursive backup when not needed

First check if we are actually going to replace the directory before
starting to do a backup of it.