Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exec.Command() in Go with environment variable

Tags:

go

exec

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?

like image 719
Vladimir Avatar asked Jan 03 '23 05:01

Vladimir


1 Answers

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.
like image 101
chuckx Avatar answered Jan 05 '23 14:01

chuckx