Golang os.Chown() Function

Golang os.Chown() function is “used to change the numeric uid and gid of the named file.”

Syntax

func Chown(name string, uid, gid int) error

Parameters

  1. name – File’s name
  2. uid – Numeric uid
  3. gid – Numeric gid

Return value

This function returns an error if the operation fails. Otherwise, it returns nil.

Example 1: How to Use os.Chown() function

package main

import (
  "fmt"
  "os"
)

func main() {
  err := os.Chown("new.txt", 1001, 1001)
  if err != nil {
    fmt.Println("Error:", err)
    return
  }
  fmt.Println("Ownership changed successfully!")
}

Output

Ownership changed successfully!

In this example, the ownership of the file “new.txt” is changed to have a user ID and group ID of 1001. If the operation is successful, it prints “Ownership changed successfully!”. Otherwise, it prints an error.

Note: You’ll need appropriate permissions to change the ownership of a file or directory. Typically, this operation is restricted to root or superuser privileges.

Example 2: Changing the ownership of a directory

package main

import (
  "fmt"
  "os"
)

func main() {
  dirPath := "new.txt"
  uid := 1002
  gid := 1002

  err := os.Chown(dirPath, uid, gid)
  if err != nil {
    fmt.Printf("Error changing ownership of directory %s: %v\n", dirPath, err)
    return
  }
  fmt.Printf("Ownership of directory %s changed successfully to UID: %d, GID: %d\n", 
               dirPath, uid, gid)
}

Output

Ownership of directory share changed successfully to UID: 1002, GID: 1002

Example 3: Changing ownership of multiple files in a slice

package main

import (
  "fmt"
  "os"
)

func main() {
  files := []string{
    "/path/to/file1",
    "/path/to/file2",
    "/path/to/file3",
  }
  uid := 1003
  gid := 1003

  for _, file := range files {
    err := os.Chown(file, uid, gid)
    if err != nil {
      fmt.Printf("Error changing ownership of file %s: %v\n", file, err)
      continue
    }
   fmt.Printf("Ownership of file %s changed successfully to UID: 
               %d, GID: %d\n", file, uid, gid)
  }
}

Output

Ownership of file /path/to/file1 changed successfully to UID: 1003, GID: 1003 
Error changing ownership of file /path/to/file2: 
   [some error message here, e.g., "no such file or directory"] 
Ownership of file /path/to/file3 changed successfully to UID: 1003, GID: 1003

That’s it!

Related posts

Golang os.Lstat()

Golang os.Stat()

Golang os.Exit()

Golang os.Chdir()

Golang os.Chmod()

Leave a Comment