Getting the owner of a file

What is the Go-way to obtain the owner of a file? I spent some time on this yesterday but found no simple solution. On poster suggested fi.Sys().(*syscall.Stat_t).Uid.

Some posts suggested that since there is no operating system independent way to do this Go has left it unimplemented. In particular there would be differences between Windows and GNU/Linux in this area.

I’ll continue to work on this today and reply to my post with the solution (if I can find one) that I wound up using.

Kind regards, -Randy

Update: I’ve decided to go with fi.Sys().(*syscall.Stat_t).Uid approach. Along the way I was reminded/learned a few things. user.Uid is a string. To get a uint32 from it one must use strconv.ParseUint() and unit32().

I also just learned about go doc. As in:
go doc strconv
Cheers, -Randy

1 Like

One really simple way is to use GitHub - bitfield/script: Making it easy to write shell-like scripts in Go

package main

import (
	"fmt"
	"github.com/bitfield/script"
)

func main() {
	owner, _ := script.Exec("ls -alhrt /usr/local/bin").Match("tcpscan").Column(3).String()
	fmt.Println("Owner of the file is", owner)
}

Output:

go run main.go
Owner of the file is rmasci

If you were on windows, you’d just check GOOS if it’s windows, mac, linux and substitute the command accordingly.

In that example, the file I was looking for was called ‘tcpscan’ – substitute for the file you’re looking for.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.