3

sometimes using rm -rf in script could be catastrophic

example

rm -rf $TMP/$folder

when TMP and $folder are without any value , it will actually

removing all under "/"

so I am asking how to use the rm -rf in the scripts so it will be safe?

marked as duplicate by Kusalananda bash Apr 7 at 6:51

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Prepending any removal operation with a check for the existence of whatever you want the script to delete would be a good start. Not using rm -r with -fis also a good idea. – Mioriin Apr 7 at 5:35
  • $folder is always with sub folders and files – yael Apr 7 at 5:36
  • Then you have the script query the system about the existence of $TMP/$folder before deleting $folder and have it abort/skip the deletion if $TMP/$folder isn't there. – Mioriin Apr 7 at 5:41
  • 1
    @Mioriin That doesn't solve the problem, because if both variables are empty (as per the question), then / will still exist. – Sparhawk Apr 7 at 6:03
  • 4
    @yael Can't you just check for non-empty variables as well before running the command? – Sparhawk Apr 7 at 6:03
2
  1. Check if $TMP and $TMP/$folder are directories
  2. Check that the canonical paths of $TMP and $TMP/$folder are different (imagine folder="" or folder="/")
  3. Check if $TMP/$folder is writable
if [ -d "$TMP" ]\
 && [ -d "$TMP/$folder" ]\
 && [ "$(readlink -e "$TMP")" != "$(readlink -e "$TMP/$folder")" ]\
 && [ -w "$TMP/$folder" ]; then
    rm -rf "$TMP/$folder"
else
    echo "Could not delete folder \"$TMP/$folder\", TMP=$TMP, folder=$folder" >&2
fi

Not the answer you're looking for? Browse other questions tagged or ask your own question.