Home  >  Article  >  Backend Development  >  How to Set Specific Environment Variables for exec.Command in Go?

How to Set Specific Environment Variables for exec.Command in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-11-16 22:56:03190browse

How to Set Specific Environment Variables for exec.Command in Go?

Setting Environment Variables for exec.Command

When working with external command line tools in Go, using exec.Command allows you to execute commands and control their environment. To pass environment variables through this function, rather than setting them system-wide, you can modify the command's environment directly.

To set a specific environment variable while retaining the existing environment, follow these steps:

  1. Initialize the exec.Command with the target command and its arguments.
  2. Retrieve the current environment using os.Environ().
  3. Append the desired environment variable to the list of environment variables (cmd.Env).

For example:

cmd := exec.Command("ansible-playbook", args...)
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "MY_VAR=some_value")

This approach ensures that only the specified variable is modified while preserving the existing environment.

The above is the detailed content of How to Set Specific Environment Variables for exec.Command in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn