logo

utils-std

Collection of commonly available Unix tools
commit: 304fbbcb9e2cdc92cc9ae5d1e47e483bb5930602
parent 7a0e72cddb82b17da2b1355405199387c10b646b
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date:   Tue, 12 Mar 2024 13:17:23 +0100

cmd/chmod: Add -v option, only fchmodat(2) on different mode

Diffstat:

Mcmd/chmod.c58+++++++++++++++++++++++++++++++++++-----------------------
1 file changed, 35 insertions(+), 23 deletions(-)

diff --git a/cmd/chmod.c b/cmd/chmod.c @@ -16,7 +16,7 @@ #include <sys/stat.h> // chmod, fstatat, S_ISDIR #include <unistd.h> // getopt -bool opt_c = false; +bool opt_c = false, opt_v = false; static int do_fchmodat(int fd, char *fdname, char *mode_arg, char *path, bool recursive) @@ -39,33 +39,42 @@ do_fchmodat(int fd, char *fdname, char *mode_arg, char *path, bool recursive) return 1; } - if(fchmodat(fd, path, mode, 0) != 0) - { - fprintf(stderr, - "chmod: Failed setting permissions to 0%6o for '%s/%s': %s\n", - mode, - fdname, - path, - strerror(errno)); - return 1; - } + char mode_from[11] = ""; + symbolize_mode(stats.st_mode, mode_from); - if(opt_c && mode != stats.st_mode) + if(mode != stats.st_mode) { - char ori_mode[11] = ""; - symbolize_mode(stats.st_mode, ori_mode); - - char cur_mode[11] = ""; - symbolize_mode(mode, cur_mode); + if(fchmodat(fd, path, mode, 0) != 0) + { + fprintf(stderr, + "chmod: Failed setting permissions to 0%6o for '%s/%s': %s\n", + mode, + fdname, + path, + strerror(errno)); + return 1; + } - printf("chmod: Mode changed from 0%o6/%s to 0%o6/%s for '%s%s'\n", + if(opt_c || opt_v) + { + char mode_to[11] = ""; + symbolize_mode(mode, mode_to); + + printf("chmod: Permissions changed from 0%o6/%s to 0%o6/%s for '%s/%s'\n", + stats.st_mode & 07777, + mode_from, + mode & 07777, + mode_to, + fdname, + path); + } + } + else if(opt_v) + printf("chmod: Permissions already set to 0%o6/%s for '%s/%s'\n", stats.st_mode & 07777, - ori_mode, - mode & 07777, - cur_mode, + mode_from, fdname, path); - } if(recursive && S_ISDIR(stats.st_mode)) { @@ -148,7 +157,7 @@ main(int argc, char *argv[]) bool opt_R = false; int c = -1; - while((c = getopt(argc, argv, ":cR")) != -1) + while((c = getopt(argc, argv, ":cRv")) != -1) { switch(c) { @@ -158,6 +167,9 @@ main(int argc, char *argv[]) case 'R': // POSIX opt_R = true; break; + case 'v': // GNU + opt_v = true; + break; case ':': fprintf(stderr, "chmod: Error: Missing operand for option: '-%c'\n", optopt); usage();