Golang os.Chmod() Function

Golang os.Chmod() function is used to change the mode of a file”. If the file is a symbolic link, it changes the mode of the link’s target. If there is an error, it will be of type *PathError.

Syntax

func Chmod(name string, mode FileMode) error

Parameters

  1. name (string): The name of the file (or directory) whose mode you want to change.
  2. mode (os.FileMode): The new mode for the file. This is a bitmask that specifies the file’s permissions.

Return value

The return type of the os.Chmod() function is an error; it returns <nil> if there is no error; otherwise, it returns an error.

Example 1: How to Use os.Chmod() Function

Here’s an example that changes the permissions of a file to be readable, writable, and executable by the owner, and just readable by everyone else.

package main

import (
  "fmt"
  "os"
)

func main() {
  filename := "new.txt"

  err := os.Chmod(filename, 0744)
  if err != nil {
    fmt.Println("Error changing file mode:", err)
    return
  }

  fmt.Printf("Changed permissions for %s successfully.\n", filename)
}

Output

Changed permissions for new.txt successfully.

Example 2: Change Permissions of Multiple Files

This code will change the permissions of multiple files to read-only for everyone.

package main

import (
  "fmt"
  "os"
)

func main() {
  files := [3]string{"data.txt",
              "npfile.txt",
              "runes.txt"}

  for _, file := range files {
    err := os.Chmod(file, 0444)
    if err != nil {
      fmt.Printf("Error changing permissions for %s: %s\n", file, err)
      continue
    }
    fmt.Printf("Changed permissions for %s to read-only.\n", file)
  }
}

Output

Changed permissions for data.txt to read-only.
Changed permissions for npfile.txt to read-only.
Changed permissions for runes.txt to read-only.

Example 3: Toggle Execute Permission for Owner

package main

import (
  "fmt"
  "os"
)

func main() {
  filename := "script.sh"

  // Get the current permissions of the file
  fileInfo, err := os.Stat(filename)
  if err != nil {
    fmt.Println("Error retrieving file info:", err)
    return
  }

  currentMode := fileInfo.Mode()
  ownerExecutePermission := os.FileMode(0100)

  if currentMode&ownerExecutePermission != 0 {
    err = os.Chmod(filename, currentMode-ownerExecutePermission)
    if err == nil {
      fmt.Printf("%s is now not executable by the owner.\n", filename)
    }
  } else {
    err = os.Chmod(filename, currentMode|ownerExecutePermission)
    if err == nil {
      fmt.Printf("%s is now executable by the owner.\n", filename)
    }
  }

  if err != nil {
    fmt.Println("Error changing file mode:", err)
  }
}

Output

Error retrieving file info: stat script.sh: no such file or directory

I got the error because of the script.sh. The file does not exist.

That’s it!

Related posts

Golang os.Getenv()

Golang os.Lstat()

Golang os.Stat()

Golang os.Exit()

Golang os.Chdir()

Leave a Comment