Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain user's home directory

Is the following the best way of obtaining the running user's home directory? Or is there a specific function that I've ovelooked?

os.Getenv("HOME") 

If the above is correct, does anyone happen to know whether this approach is guaranteed to work on non-Linux platforms, e.g. Windows?

like image 573
Paul Ruane Avatar asked Oct 27 '11 20:10

Paul Ruane


People also ask

How do I find the user home directory?

String userHome = System. getProperty( "user. home" ); to get the home directory of the user on any platform.

How do I find the home directory of a user in Windows?

Starting with Windows Vista, the Windows home directory is \user\username. In prior Windows versions, it was \Documents and Settings\username. In the Mac, the home directory is /users/username, and in most Linux/Unix systems, it is /home/username.

How do I find the home directory in Linux?

To navigate to your home directory, use "cd" or "cd ~" To navigate up one directory level, use "cd .." To navigate to the previous directory (or back), use "cd -" To navigate through multiple levels of directory at once, specify the full directory path that you want to go to.

What is user's home directory in Linux?

The home directory is a subdirectory of the root directory. It is denoted by a slash '/'. It is denoted by '~' and has path "/users/username". The admin has access to make any changes in the files and settings.


1 Answers

Since go 1.12 the recommended way is:

package main import (     "os"     "fmt"     "log" ) func main() {     dirname, err := os.UserHomeDir()     if err != nil {         log.Fatal( err )     }     fmt.Println( dirname ) } 

Old recommendation:

In go 1.0.3 ( probably earlier, too ) the following works:

package main import (     "os/user"     "fmt"     "log" ) func main() {     usr, err := user.Current()     if err != nil {         log.Fatal( err )     }     fmt.Println( usr.HomeDir ) } 
like image 154
Vlad Didenko Avatar answered Oct 07 '22 09:10

Vlad Didenko