File Mode Permission Bit Inspection

os.FileMode packs type and permission bits: String renders them rwx style, Perm strips the type bits, and IsDir or IsRegular classify the mode.

GoSecurity Boundaries

Code

snippet
package main

import (
	"fmt"
	"os"
)

func main() {
	// FileMode packs type bits (dir, symlink, ...) and rwx permission bits
	regular := os.FileMode(0o644)
	fmt.Println("regular:", regular.String())

	dir := os.ModeDir | 0o755
	fmt.Println("dir:", dir.String())

	// Perm keeps only the permission bits
	fmt.Println("dir perm:", dir.Perm().String())

	fmt.Println("is dir?", dir.IsDir(), "is regular?", regular.IsRegular())

	// flip single permission bits
	m := os.FileMode(0o664)
	m &^= 0o020
	m |= 0o001
	fmt.Println("after edits:", m.String())
}

What the demo inspects

os.FileMode is a bitfield that packs type and permission bits together. The demo builds a plain 0644 mode and a directory mode from os.ModeDir | 0755, then prints both through String, which renders the rwx-style form: -rw-r–r– for the regular file, drwxr-xr-x for the directory.

Perm() masks the type bits off and prints the bare permission set for the directory, IsDir and IsRegular classify the two values, and the closing lines edit single bits: &^= clears group write, |= sets other-execute, and the after edits line shows 0645 with both changes visible in one string.

Caveats and details

  • String() renders type and permission bits together, like -rw-r–r– for 0644.
  • Perm() masks the type bits off with 0777 before printing.

Interactive Tools for This Topic

FAQ

What does m &^= 0o020 do to the FileMode?
It clears the group-write bit with Go's AND NOT operator; the printed after edits mode shows 0645, because 0o001 then sets the other-execute bit on top.