Creating files and directories with a certain owner (user/group) while sudoing

You can always sudo -u username touch filename when your script is executed as root. It usually requires no password, depending on your sudoers configuration.

Alternatively, run su username -c touch filename. The additional arguments are supplied to the user's shell, and the -c option to the shell executes the specified commands by convention.


Some commands (like mkdir) support arguments to specify the permissions:

mkdir -m 0700 foo

By default, file operations respect the umask set for the shell. It defines which permissions are denied. A umask of 0022 for example does not set write permissions for group and others. Set to 0077 to prevent group and others from getting any permissions.


You can set the setgid on directories to have all files created within inherit their group membership:

chmod g+s someDir

Some Unixes support the same behavior for setuid (chmod u+s), but not Linux.


There is another way, quite elegant I think. Using install(1)

For example, zabbix-agentd needs a subfolder inside /var/run, but recent distributions are using tmpfs for /var/run, so the directory does not survive reboots. I solved it by creating a file /etc/sysconfig/zabbix-agentd containing:

install -g zabbix -o zabbix -d /var/run/zabbix

On Unix-like systems newly created files and directories are owned by the owner of the process which created them. Standard utilities normally do not have option to change the owner of the created files.

Variables with UID and GID of the original user

If you run some commands repeatedly, you can use the variables $SUDO_UID and $SUDO_GID to refer to the user who invoked sudo:

sudo sh -c "do_something ; chown -R \"\$SUDO_UID:\$SUDO_GID\" files and directories"

Getting the list of created files and directories automatically

If you want to get the list of created (and possibly modified) files and directories automatically you can run your commands under strace surveillance which is based on the ptrace() syscall:

strace -qqfe open,creat,mkdir,link,symlink,mknod -o '|your_processing_of_strace_output' do_something

or you can use for example Installwatch which is based on the LD_PRELOAD mechanism.

Ideas for further work

Based on the methods mentioned above it is possible to create a tool which would automatically change the owner and possibly access rights of the created/modified files. The use could be as simple as:

sudo watch-chown do_something