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?

yael
  • 13,106
  • 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. – Mio Rin Apr 07 '19 at 05:35
  • $folder is always with sub folders and files – yael Apr 07 '19 at 05: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. – Mio Rin Apr 07 '19 at 05: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 07 '19 at 06:03
  • 4
    @yael Can't you just check for non-empty variables as well before running the command? – Sparhawk Apr 07 '19 at 06:03
  • In addition to checking for non-empty variables, run du to verify that the target directory is not larger than you expect. – John1024 Apr 07 '19 at 06:04
  • Tip one: use quotes. Tip two: prepend with / or ./ – ctrl-alt-delor Apr 07 '19 at 10:02

1 Answers1

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
Freddy
  • 25,565