I would like to run following code in Go:
out, err := exec.Command("echo", "$PATH").Output()
The result was:
$PATH
Instead of the expected value of "PATH=/bin...".
Why? And how can I get the expected value?
Your command is not being interpreted by a shell, which is why the expected variable substitution is not occurring.
From the exec
package documentation:
...the os/exec package intentionally does not invoke the system shell and does not expand any glob patterns or handle other expansions, pipelines, or redirections typically done by shells.
...
To expand environment variables, use package os's ExpandEnv.
So to achieve the desired result in your example:
out, err := exec.Command("echo", os.ExpandEnv("$PATH")).Output()
It's worth reviewing the set of functions for getting environment variables and using what works best for your particular use case:
func ExpandEnv(s string) string
- ExpandEnv replaces ${var} or $var in the string according to the values of the current environment variables. References to undefined variables are replaced by the empty string.func Getenv(key string) string
- Getenv retrieves the value of the environment variable named by the key. It returns the value, which will be empty if the variable is not present. To distinguish between an empty value and an unset value, use LookupEnv.func LookupEnv(key string) (string, bool)
- LookupEnv retrieves the value of the environment variable named by the key. If the variable is present in the environment the value (which may be empty) is returned and the boolean is true. Otherwise the returned value will be empty and the boolean will be false.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