Help us understand the problem. What is going on with this article?

cmd.Envを設定してexecしたらコケた

More than 3 years have passed since last update.

goのexecでrubyのgemを叩いてた時にハマる。

// rubyのTDを叩きたい!
cmd := exec.Command("td", args...)
// 環境変数設定
cmd.Env = []string{"SOME_PROP=0"}

// 実行
out, _ := cmd.CombinedOutput()

解決

cmd := exec.Command("td", args...)
// 既存の設定を取得して結合
cmd.Env = append(os.Environ(), "SOME_PROP=0")

out, _ := cmd.CombinedOutput()

原因

command.Envに環境変数を設定すると既存の変数はクリアされます。(よく考えれば当たり前か)
自分のケースでは環境変数がクリアされた状態でrbenvのgemを叩きにいってエラー

それを避けるためために既存の変数をos.Environ()で取得して、設定したい環境変数を追加した上で再設定しました。

参考

Go: command with custom environment

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away