Create a file as a different user and group

If you want to create a file as a specific user and group without using chown, you can use sudo and specify the user and group:

sudo -u \#49 -g \#58 touch /tmp/something

Note that the user you specify must have permission to write to the directory where you attempt this.


Or, you can start a shell as the current user, with the group set to something else:

sudo runuser "$USER" -g somegroup

I tried this on a Vagrant box with success:

[vagrant@localhost ~]$ sudo runuser "$USER" -g floppy
[vagrant@localhost ~]$ touch testfile
[vagrant@localhost ~]$ ls -l testfile
-rw-r--r--. 1 vagrant floppy 0 Nov  9 15:57 testfile
[vagrant@localhost ~]$ 

This is despite the "vagrant" user not being part of the "floppy" group.


$ sudo install -o angelo -g apache /dev/null angelo-file

Works for me on centos 6, install version 8.4. Here the install is "copying" the (known to always be empty) /dev/null file to the target, thereby creating your empty file, while in same/single command setting target file's owner and group, because it's run as root via sudo.

Read more about it via: man install or install --help. It can create directories, and set permission modes too, in same/single command. The install command is frequently used in build tools, like makefiles.

You may like to use option -T too, so if target preexists but is a directory, it will fail with an error, and not create empty angelo-file/null instead.

EDIT: OP asked about rsync, duh. Since rsync 3.1.2 see the options like --chmod, --chown, --usermap, --groupmap. (For centos 6 I can get the newer rsync from the iUS repo).