How do I check a file's permissions in linux using Go

Viewed 10924

I'm learning Go and the first project I want to do is to write a replacement for the Linux find shell program. I wrote a replacement for it in python in less than an hour. This is a much bigger challenge.

The problem I'm having is as Goes filepath.Walk traverses my file system it spits out a bunch of permission denied messages to the screen. I need a way of checking the files permissions before filepath.Walk touches them.

3 Answers

You can retrieve the permissions in string form e.i: r, w, x. Like this:

func printPermissions(filename string) {
    info, err := os.Stat(filename)
    if err != nil {
        panic(err)
    }

    mode := info.Mode()

    fmt.Print("Owner: ")
    for i := 1; i < 4; i++ {
        fmt.Print(string(mode.String()[i]))
    }

    fmt.Print("\nGroup: ")
    for i := 4; i < 7; i++ {
        fmt.Print(string(mode.String()[i]))
    }

    fmt.Print("\nOther: ")
    for i := 7; i < 10; i++ {
        fmt.Print(string(mode.String()[i]))
    }
}

For unix permissions and modern go you can use literals.

filePath := "/tmp/testfile"
fileStats, err := os.Stat(filePath)
if err != nil {
    log.Fatalf("file does not exist: %v", err)
}

permissions := fileStats.Mode().Perm()
if permissions != 0o600 {
    log.Fatalf("incorrect permisisons %s (0%o), must be 0600 for '%s'", permissions, permissions, filePath)
}

// check for specific permissions: user read, user write
if permissions&0b110000000 == 0b110000000 {
    fmt.Printf("user has read and write permission\n")
}

// check for specific permission: user write
if permissions&0b010000000 == 0b010000000 {
    fmt.Printf("user has write permission\n")
}

// check for specific permission: user read
// breakup for better readability
if permissions&0b100_000_000 == 0b100_000_000 {
    fmt.Printf("user has read permission\n")
}

A nice explaination on permissions as bits and octal
https://codereview.stackexchange.com/a/79100

Related