script-files-permissions-set 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #!/usr/bin/env bash
  2. # Intelligently change permissions on selected directories
  3. # Copyright 2021-2025 Bryan C. Roessler
  4. # Licensed under the Apache License, Version 2.0
  5. p="${BASH_SOURCE[0]%/*}"; [[ -r $p/script-functions ]] && . "$p"/script-functions || exit 1
  6. is_root
  7. if [[ $# -eq 0 ]]; then
  8. echo "No arguments provided, using autodetection"
  9. paths=("$PWD")
  10. user=$(stat -c "%U" "$PWD")
  11. group=$(stat -c "%G" "$PWD")
  12. elif [[ $# -eq 1 ]]; then
  13. user="$1"
  14. group="$1"
  15. paths=("$PWD")
  16. elif [[ $# -eq 2 ]]; then
  17. user="$1"
  18. group="$2"
  19. paths=("$PWD")
  20. elif [[ $# -gt 2 ]]; then
  21. user="$1"
  22. group="$2"
  23. paths=("${@:3}")
  24. fi
  25. for path in "${paths[@]}"; do
  26. if [[ "$path" == "/" ]]; then
  27. echo "You are trying to operate on the root partition!"
  28. echo "This seems highly unusual!"
  29. ask_ok "Continue?" || exit $?
  30. fi
  31. og_user=$(stat -c "%U" "$path")
  32. og_group=$(stat -c "%G" "$path")
  33. printf "%-20s %-10s %-10s\n" "PATH" "USER" "GROUP"
  34. echo -e "$path\t$og_user\t$og_group"
  35. if [[ "$group" != "smbgrp" || "$og_group" != "smbgrp" ]]; then
  36. echo "$path is not world accessible by the smbgrp group"
  37. ask_ok "Change $path group $og_group to smbgrp?" && group="smbgrp"
  38. fi
  39. done
  40. ask_ok "Apply user: $user and group: $group to ${paths[*]} and all subdirs?" && \
  41. chown -R "$user":"$group" "${paths[@]}"
  42. # Set mode based on group:
  43. # - 6775: Enables read/write/execute for owner and group, with setgid bit for group inheritance.
  44. # - 755: Enables read/write/execute for owner, and read/execute for group and others.
  45. [[ "$group" == "smbgrp" ]] && mode=6775 || mode=755
  46. ask_ok "Apply chmod $mode to ${paths[*]} and all subdirs?" && \
  47. chmod -R "$mode" "${paths[@]}"
  48. # Let's do it in less steps (see above) for now unless it becomes a problem
  49. # TODO: Implement setuid/setgid functionality to ensure files and directories inherit user/group permissions.
  50. # echo "Apply setuid/setgid bits to ${paths[*]} and all subdirs?"
  51. # ask_ok "Files/dirs will inherit their " && \
  52. # chmod -R g+s,u+s "${paths[@]}"