13

I'm trying to create a directory using os.Mkdir() and then create files in it, similar to this script:

package main

import (
    "log"
    "os"
    "path"
)

func main() {
    dir := "test_dir"

    os.Mkdir(dir, os.ModeDir)

    fileName := path.Join(dir, "file.txt")

    _, err := os.Create(fileName)
    if err != nil {
        log.Fatalf("create file: %v", err)
    }
}

However, if I run this, I get

> go run fileperms.go
2019/10/15 14:44:02 create file: open test_dir/file.txt: permission denied
exit status 1

It is not immediately clear to me from https://golang.org/pkg/os/#FileMode how to specify the FileMode in order to allow the same script to create files in the newly-created directory. How can I achieve this?

2
  • 2
    Almost all calls to os.Mkdir should pass 0777 as the second argument. You don't need os.ModeDir as it's implied by the make-directory function. The low 3 bits are Unix-style permissions; it's up to the OS to translate them to whatever the OS uses. On Unix-like systems, the current umask will take away any unwanted permissions, so you should usually grant all permissions to everyone to start. Commented Oct 15, 2019 at 22:08
  • 2
    Exceptions to this rule include, e.g., a mail message handler, where you might assume user-level privacy and use mode 0700: rwx for user, nothing for group or other. A typical umask is 002 or 022, to take away other, and maybe group, write permission. Commented Oct 15, 2019 at 22:09

2 Answers 2

20

I found that I am able to create files in the directory if I set the permission to 0777:

package main

import (
    "io/ioutil"
    "os"
    "path"
)

func main() {
    dir := "test_dir"

    os.Mkdir(dir, 0777)

    fileName := path.Join(dir, "file.txt")

    ioutil.WriteFile(fileName, []byte("foobar"), 0666)
}

Now the file is created with the expected content:

> cat test_dir/file.txt 
foobar⏎ 
Sign up to request clarification or add additional context in comments.

3 Comments

after hours of searching and trial error, this one truely solved my problem! PS: I was using 662, 420, 666, 777, but none of them worked, especially for directories
there is no case you need to use 777 as it is wide permission. it is considered not secure. please check this link superuser.com/questions/1034079/…
@YasserSinjab I agree that 777 doesn't sound like a good idea, but I'm facing the same issue and so far 0777 seems to be the only thing that's working. Do you have any other approaches you could suggest?
4

Here, Go was trying to create inside /tmp directory during an AUR package installation.

So I've changed the permissions in /tmp:

chmod 0777 -R /tmp

But that was not enough, so I had to change /tmp ownership (it was root's):

sudo chown -R "$USER":wheel /tmp

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.