How to get the current username and directory in Golang?


Sometimes there are cases where we want to know which user is executing the current program and in which directory and we can get all these details with the help of the user package that is present inside the os package of Go's standard library.

In this article, we will explore three such cases, where first, we will log out the username who is executing the current process and then we will log out the name along with the id and finally, we will log out from the directory in which the current program is located.

Getting the Username

To get the username, we simply call the Current() function that will return the current user. Consider the code shown below.

package main

import (
   "fmt"
   "log"
   "os/user"
)

func main() {
   currentUser, err := user.Current()
   if err != nil {
      log.Fatalf(err.Error())
   }

   username := currentUser.Username

   fmt.Printf("Username is: %s\n", username)
}

Output

If we run the command go run main.go on the above code, then we will get the following output in the terminal.

Username is: apache

Getting the Name and ID

To get the name of the user and the id, we call the Name() and Uid() function, respectively, on the current user. Consider the code shown below.

package main

import (
   "fmt"
   "log"
   "os/user"
)

func main() {
   currentUser, err := user.Current()
   if err != nil {
      log.Fatalf(err.Error())
   }

   name := currentUser.Name
   id := currentUser.Uid

   fmt.Printf("name is: %s and id is: %s\n", name, id)
}

Output

If we run the command go run main.go on the above code, then we will get the following output in the terminal.

name is: Apache and id is: 48

Getting the Current Directory

To get the current directory, we simply need to call the HomeDir() function on the current user. Consider the code shown below.

package main

import (
   "fmt"
   "log"
   "os/user"
)

func main() {
   currentUser, err := user.Current()
   if err != nil {
      log.Fatalf(err.Error())
   }

   dir := currentUser.HomeDir

   fmt.Printf("dir is: %s\n", dir)
}

Output

If we run the command go run main.go on the above code, then we will get the following output in the terminal.

dir is: /usr/share/httpd

Updated on: 01-Nov-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements