Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go - os.UserHomeDir() returning " C:\Users\<user_name>" on WSL

I'm learning and trying out golang to create an application that needs access to user home directory.

To make easier to understand the problem, consider this main.go:

package main

import (
    "fmt"
    "os"
)

func main() {
    home, err := os.UserHomeDir()
    if err != nil {
        fmt.Printf("Err: %s\n", err)
        os.Exit(1)
    } else {
        fmt.Printf("HOME: %s\n", home)
        os.Exit(0)
    }
}

After building the application I tried to run it on windows and macos and the output worked well.

For linux, I tried to run on WSL, I don't know if that's the problem HOME: C:\Users\<user>

  • On wsl I've tried to echo $HOME and it showed the correct homedir.
  • Also to get os.Getenv("HOME") and was printing empty
  • Also tried to PrintAll envs and there was no HOME environment variable. Actually, there was no linux environment variable, only windows

Update

  • To build the application I'm using the following command on my windows machine
go build -o C:/_builds/.bin/example .
  • Then I navigate to this folder using according to the windows mount in wsl.
 cd /mnt/c/_builds/.bin

And run the command

./example

Here is the output terminal output_terminal

I've ommited my machine information and username

Do you have any ideas? Am I missing something?

like image 684
Vinicius Andrade Avatar asked Nov 15 '25 11:11

Vinicius Andrade


1 Answers

You're building a Windows binary.

When you execute it in the WSL environment, it's still a Windows binary, still retains the runtime.GOOS value set at compile time, and will still trigger the Windows specific code path in the os.UserHomeDir() implementation.


To build a Linux binary, try setting the GOOS environment variable before running the go build command. Something like:

set GOOS="linux"
go build -o C:/_builds/.bin/example_linux .

The full set of environment variables that influence operation of the go command are documented at https://pkg.go.dev/cmd/go#hdr-Environment_variables.


For background on WSL supporting execution of Windows executables see https://learn.microsoft.com/en-us/windows/wsl/filesystems#run-windows-tools-from-linux.

like image 143
chuckx Avatar answered Nov 17 '25 08:11

chuckx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!