8

In a bash script I want to recursively chown all subfolders of an arbitrary folder with the user and group owners of that given folder.

My approach is something like using stat -c "%U %G" .

But that returns only a pattern of username[whitespace]groupname

Of course I could just try different tools to replace the whitespace with a : but I would prefer to use a more "built-in" way if there is one, to just apply current ownership to the sub folders.

6

chown, like chmod, can use a reference:

chown [OPTION]... --reference=RFILE FILE...

Change the owner and/or group of each FILE to OWNER and/or GROUP.  With
--reference, change the owner and group of each FILE to those of RFILE.

So:

chown --reference=/some/folder -R /some/folder
8

You don't actually need to parse the output to remove the whitespace - you added that in your command! You can just format it as you like (with chown's colon syntax) in the first place:

$ stat -c "%U:%G" .
zanna:unicorns

So just pass that to chown with command substitution:

chown -R $(stat -c "%U:%G" .) .
  • Sometimes I am just blind for the obvious. Thank you! – Jankapunkt Sep 8 '17 at 15:26

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.