Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively create a directory with a certain owner and group

Tags:

go

I would like to recursively create a directory and assign an owner and group for the folders and its parents that were created.

For example, assuming /var exists, I want to create /var/test1/test2/test3.

I am able to do this using os.MkdirAll("/var/test1/test2/test3", 0600).

However, I also want to set test1, test2, and test3's uid to user1 and gid to user1.

It's possible to do so using os.Chown, but that requires a lot of manually work. I would need build a tree of the folder and its parents that do not exist before creating the folder chain and then use os.Chown on each folder after creation.

Is there a simpler way?

like image 369
F21 Avatar asked Sep 06 '25 04:09

F21


1 Answers

A bit like this ChownR() type of function, the idea would be to filter the walk, and apply the chown only to folders which are part of a path passed in parameter (here "/var/test1/test2/test3)

Without filter:

func ChownR(path string, uid, gid int) error {
    return filepath.Walk(path, func(name string, info os.FileInfo, err error) error {
        if err == nil {
            err = os.Chown(name, uid, gid)
        }
        return err
    })
}

In other words, with filepath.Walk(), there should not be too much "manual work" involved here.

like image 52
VonC Avatar answered Sep 08 '25 18:09

VonC