Home > Net >  chgrp of files in a directory based on the filename
chgrp of files in a directory based on the filename

Time:08-04

I'm stuck with a lot of files requiring a chgrp to change group from root to the group which needs to be taken from the filename, here is an example file list:

-rw-r----- 1 root root           412K Aug  3 10:44 alexa.sqlite
-rw-r----- 1 root root           3.9M Aug  3 10:44 beta.sqlite
-rw-r----- 1 root root            16M Apr  2 21:34 carlo.sqlite
-rw-r----- 1 root root            66M Aug  3 10:44 delta.sqlite
-rw-r----- 1 root root           2.5M Aug  3 05:40 zeta.sqlite

I need to change the group of these to be owned by the filename before the .sqlite part, so desired output is:

-rw-r----- 1 root alexa           412K Aug  3 10:44 alexa.sqlite
-rw-r----- 1 root beta            3.9M Aug  3 10:44 beta.sqlite
-rw-r----- 1 root carlo            16M Apr  2 21:34 carlo.sqlite
-rw-r----- 1 root delta            66M Aug  3 10:44 delta.sqlite
-rw-r----- 1 root zeta            2.5M Aug  3 05:40 zeta.sqlite

individually the command would be:

chgrp zeta zeta.sqlite

But need to loop through every file/filename, stumped by this currently, any help greatly appreciated, thanks.

CodePudding user response:

#!/bin/bash
shopt -s nullglob
for f in *.sqlite; do
  if ! chgrp "${f%.sqlite}" "$f"; then
    echo "$f ownership cannot be changed."
  fi
done

Run it in the directory with .sqlite files.

Note: shopt is there to prevent errors if there are no .sqlite files.

  • Related