Advertisement
hxrussia

Remove executables recursively in Linux (using Bash)

Dec 26th, 2014
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.28 KB | None | 0 0
  1. #!/usr/bin/env bash
  2.  
  3. declare -a files
  4. declare -i total_count=0
  5. declare -i exec_size=0
  6. declare -i total_size=0
  7.  
  8. desired_type="x-executable; charset=binary"
  9.  
  10. function check {
  11.     local filepath="$1"
  12.     local -i size="`stat --format="%s" "$filepath"`"
  13.     (( total_count++ ))
  14.     (( total_size += size ))
  15.     if file --mime "$filepath" | grep "$desired_type" > /dev/null; then
  16.         files+=("$filepath")
  17.         (( exec_size += size ))
  18.         echo $filepath
  19.     fi
  20. }
  21.  
  22. function find {
  23.     local directory="$1"
  24.     for elem in "$directory"/*; do
  25.         if [[ -d "$elem" ]]; then
  26.             find "$elem"
  27.         elif [[ -f "$elem" ]]; then
  28.             check "$elem"
  29.         fi
  30.     done
  31. }
  32.  
  33. declare -i base
  34. (( base = 1024 ** 2 ))
  35.  
  36. function print_size {
  37.     LC_ALL=C printf '%.1lf MiB' `echo "$1" / $base | bc --mathlib`
  38. }
  39.  
  40.  
  41. if [[ -z "$1" ]]; then
  42.     directory=.
  43. else
  44.     directory="`echo "$1" | sed -r 's,/$,,'`"
  45. fi
  46.  
  47. echo '[*] Search for files...'
  48. find "$directory"
  49. label="[*] Directory contains %d files (total size %s)\n"
  50. printf "$label" $total_count "`print_size $total_size`"
  51. label="[?] Are you sure to remove %d files (total size %s)? [yes/no]\n"
  52. printf "$label" ${#files[@]} "`print_size $exec_size`"
  53. read -r
  54. if [[ "$REPLY" == "yes" ]]; then
  55.     rm --force "${files[@]}"
  56.     echo "[+] Operation complete"
  57. else
  58.     echo "[*] Operation canceled"
  59. fi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement