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?
String userHome = System. getProperty( "user. home" ); to get the home directory of the user on any platform.
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.
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.
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.
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 ) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With