4

In a build script I want to create a temporary file that has a unique generated name, then write some data to it, and then rename that file to its final name (the reason for this procedure is that I want the renaming to happen (mostly) atomic).

But if I use mktemp, the new file will have very restrictive permissions:

Files are created u+rw, and directories u+rwx, minus umask restrictions.

... and these permissions will be preserved when the file is renamed. However, I want the resulting file to have "normal" permissions; that is, it should have the same permissions as files created by touch or by a shell redirection.

What is the recommended way to achieve this? Is there a (common) alternative to mktemp; or is there a simple and reliable way to change the file permissions to the normal umask permissions afterwards?

oliver
  • 458
  • 3
  • 9

2 Answers2

4

You can use chmod =rw "$file" after creating the temp file. The GNU man page says:

A combination of the letters ugoa controls which users' access to the file will be changed: [...] If none of these are given, the effect is as if (a) were given, but bits that are set in the umask are not affected.

So, =rw gives read-write permissions reduced by the umask, similar to passing 0666 as the permissions argument to open(), which is what e.g. touch filename, or echo > filename would do.

That's a POSIX feature, so other implementations should support it too.

ilkkachu
  • 138,973
0

Use this link to get the desired permissions you want http://permissions-calculator.org/

Manual

Create a script file that creates a new file, then changes its permissions.

#!/bin/bash

Filename=$1 Perms=$2

#Create a temp file touch $Filename

#Change the file's permissions (Use your own desired permissions) chmod $Perms $Filename

After making the script executable chmod +x myscript.sh, execute the script file like this ./myscript.sh tempfile 600

Using Umask (Don't Recommend)

you can temporarily change the default file permissions using umask 600 for example.

To permanently change the default file permissions, edit your .bashrc file in your user's root directory.

nano ~/.bashrc

add umask 600 to the bottom of the file. Ofcourse, make sure to match your desired permissions. Make sure you edit the correct user as well.

If this is for a build script, I would use the manual method instead of relying on umask. Especially if your build script will be used on different systems.

Toasty140
  • 131
  • 1
    umask probably doesn't help with mktemp. At least the GNU version says "Files are created u+rw, and directories u+rwx, minus umask restrictions.", so you can't use the umask to get permissions for group and others – ilkkachu May 25 '21 at 14:54
  • You are right, i included it just because they asked about it in the question. I updated the answer to reflect that ^^ – Toasty140 May 25 '21 at 15:06