I'm running Ubuntu 24.04.1 LTS distro on Windows via WSL but when I run:
myBoolEnv := os.Getenv("MY_BOOLEAN_ENV_VAR")
fmt.Printf("** [first]%s[second]\n", myBoolEnv)
And then on Window PowerShell terminal, I logged into the Linux instance session:
> wsl -d "Ubuntu-24.04"
And ran the file containing the code above with the following command:
> go run .
But then it showed this result:
[second]t]true
Also if I changed the line to:
fmt.Printf("** [1]%s[2]\n", myBoolEnv)
The output is:
[2][1]true
But if I use:
fmt.Printf("** %s\n", myBoolEnv)
Then it works:
** true
Also, when I print the environment using echo $MY_BOOLEAN_ENV_VAR
, it still outputs true
.
This creates problem for me because later on the application code converts the myBoolEnv
using strconv.ParseBool()
and it always returns false
.
My colleague using native Linux without WSL doesn't suffer from this issue (though I don't have the opportunity to switch to native Linux).
Could you help to explain why this happens and how to fix it?
The issue is because of Windows and Linux handle line endings differently (CRLF vs LF). The value you read from the code is most likely set by a Windows process, causing the above code to interpret it as containing \r\n
after the actual value.
By using strings.TrimSpace(), all the leading and trailing white space characters are removed, and thus you will be able to read the actual value only.