I'm working on a script that downloads a file with bar:bar ownership, then changes the ownership to foo:server. So I wrote a side script(chown_test.sh) to implement the changing of the ownership via chown. Once working I'll inject it into the main script, but I've run into a problem (shown below) probably due to my lack of experience using chown.
Note: I tried to include all the necessary information below, but if you need more information just let me know via a comment.
Directory structure, ownerships and permissions:
+ drwxrwxr-x 2 foo:server chown_test # test directory
├─ -rwxrwxr-- 1 foo:server chown_test.sh # side script
├─ -rwxrwxr-- 1 bar:bar file # empty file
Relevant entries from /etc/group:
sudo:x:27:foo
bar:x:33:foo
foo:x:1000:
server:x:1003:bar,foo
The chown_test.sh code:
#!/bin/bash
echo "User: $USER"
chown foo:server ./file
I've also tried sudo chown foo:server ./file but that prompts me to enter a sudo password for bar, which doesn't have a sudo password.
Output of running chown_test.sh as bar:
[16:13 foo@Opus]:~/chown_test$ sudo -H -u bar bash -c ./chown_test.sh
User: bar
chown: changing ownership of ‘./file’: Operation not permitted
Output of running chown_test.sh as foo:
[16:14 foo@Opus]:~/chown_test$ ./chown_test.sh
User: foo
chown: changing ownership of ‘./file’: Operation not permitted
Could someone please shed some light on my dilemma?
Thank you for reading my question.
Update:
With help from Toby Speight's answer and comments, I arrived at a happy medium.
Since, "Only a privileged process (Linux: one with the CAP_CHOWN capability) may change the owner of a file. The owner of a file may change the group of the file to any group of which that owner is a member.", then I just decided to only change the group, not the owner.
I did this by changing the chown command in chown_test.sh to:
chown :server ./file
and the result:
├─ -rwxrwxr-- 1 bar:server file
Which is suitable for me, but if it's unsuitable for you then have a look at Toby Speight's answer below for more information.
chown- e.g. I know that HP/UX only allows root to change ownership, but Linux allows the owner to change the group (within limits - see thechown(2)man page.