perms.plugin.zsh 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # Some useful commands for setting permissions.
  2. #
  3. # Rory Hardy [GneatGeek]
  4. # Andrew Janke [apjanke]
  5. ### Aliases
  6. # Set all files' permissions to 644 recursively in a directory
  7. alias set644='find . -type f ! -perm 644 -print0 | xargs -0 chmod 644'
  8. # Set all directories' permissions to 755 recursively in a directory
  9. alias set755='find . -type d ! -perm 755 -print0 | xargs -0 chmod 755'
  10. ### Functions
  11. # fixperms - fix permissions on files and directories, with confirmation
  12. # Returns 0 on success, nonzero if any errors occurred
  13. fixperms () {
  14. local opts confirm target exit_status chmod_opts use_slow_mode
  15. zparseopts -E -D -a opts -help -slow v+=chmod_opts
  16. if [[ $# > 1 || -n "${opts[(r)--help]}" ]]; then
  17. cat <<EOF
  18. Usage: fixperms [-v] [--help] [--slow] [target]
  19. target is the file or directory to change permissions on. If omitted,
  20. the current directory is taken to be the target.
  21. -v enables verbose output (may be supplied multiple times)
  22. --slow will use a slower but more robust mode, which is effective if
  23. directories themselves have permissions that forbid you from
  24. traversing them.
  25. EOF
  26. exit_status=$(( $# > 1 ))
  27. return $exit_status
  28. fi
  29. if [[ $# == 0 ]]; then
  30. target="."
  31. else
  32. target="$1"
  33. fi
  34. if [[ -n ${opts[(r)--slow]} ]]; then use_slow=true; else use_slow=false; fi
  35. # Because this requires confirmation, bail in noninteractive shells
  36. if [[ ! -o interactive ]]; then
  37. echo "fixperms: cannot run in noninteractive shell"
  38. return 1
  39. fi
  40. echo "Fixing perms on $target?"
  41. printf '%s' "Proceed? (y|n) "
  42. read confirm
  43. if [[ "$confirm" != y ]]; then
  44. # User aborted
  45. return 1
  46. fi
  47. # This xargs form is faster than -exec chmod <N> {} \; but will encounter
  48. # issues if the directories themselves have permissions such that you can't
  49. # recurse in to them. If that happens, just rerun this a few times.
  50. exit_status=0;
  51. if [[ $use_slow == true ]]; then
  52. # Process directories first so non-traversable ones are fixed as we go
  53. find "$target" -type d ! -perm 755 -exec chmod $chmod_opts 755 {} \;
  54. if [[ $? != 0 ]]; then exit_status=$?; fi
  55. find "$target" -type f ! -perm 644 -exec chmod $chmod_opts 644 {} \;
  56. if [[ $? != 0 ]]; then exit_status=$?; fi
  57. else
  58. find "$target" -type d ! -perm 755 -print0 | xargs -0 chmod $chmod_opts 755
  59. if [[ $? != 0 ]]; then exit_status=$?; fi
  60. find "$target" -type f ! -perm 644 -print0 | xargs -0 chmod $chmod_opts 644
  61. if [[ $? != 0 ]]; then exit_status=$?; fi
  62. fi
  63. echo "Complete"
  64. return $exit_status
  65. }