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