Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

go

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.

like image 288
Ricky Wilson Avatar asked Dec 24 '22 15:12

Ricky Wilson


1 Answers

In go the file permission is defined in os.FileMode in which the underlying type is an uint32. From documentation:

A FileMode represents a file's mode and permission bits...
...
The defined file mode bits are the most significant bits of the FileMode. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

You can retrieve the FileMode through os.Stat or os.LStat function which returns a FileInfo, e.g.

info, err := os.Stat("file/directory name")

then the FileMode can be obtained by calling info.Mode(). To check the permission, performs bitwise operation to the mode bits, e.g.

//Check 'others' permission
m := info.Mode()
if m&(1<<2) != 0 {
    //other users have read permission
} else {
    //other users don't have read permission
}

If you're visiting directory/file(s) using filepath.Walk function, since the WalkFunc (the second argument of Walk) is defined as

type WalkFunc func(path string, info os.FileInfo, err error) error

the FileInfo for certain path is available as the second argument of WalkFunc, thus you can check the permission directly using info.Mode() without calling os.Stat or os.Lstat inside the body of the closure or function passed to filepath.Walk.

like image 191
putu Avatar answered Dec 26 '22 04:12

putu