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

chmodchownlinuxpermissionsroot

I need to wget something (results in a compressed file in cwd), then I have to extract it, then do some copy/move/modification stuff and perhaps finally execute an script (from the downloaded archive).

Now all these task either directly (wget, extract etc.) or indirectly (running the script) result in creating files and directories (all in the current working directory). I do all this stuff as root (no way to do it with the final, desired user).

The problem is: Anything created in the process is owned by root or the sudo user. When I'm done (and sometimes in the mid-way), I have to issue a series of chmod and chown commands to make things right.

Now it would be nice if could somehow tell the system that "From now on, any files or dirs that you create when I issue commands as root, you would create with such and such ownership and permissions".

Best Answer

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.

Related Question