Skip to content

Commit 5a72b6e

Browse files
committed
Add cmdexec/withenv.go
1 parent 007c0e3 commit 5a72b6e

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

examples/basic/cmdexec/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@
1010
|withcontext.go|cmdexec\_withcontext|コマンドを context.Context 付きで実行するサンプルです|
1111
|pipe.go|cmdexec\_pipe|(*Cmd).StdinPipe,StdoutPipe,StderrPipeのサンプルです|
1212
|multi\_command\_with\_pipe.go|cmdexec\_multi\_command\_with\_pipe|複数の (*exec.Cmd) をパイプストリームで繋いで実行するサンプルです|
13+
|withenv.go|cmdexec\_env|*exec.Cmd 実行時に追加の環境変数を指定するサンプルです|

examples/basic/cmdexec/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,5 @@ func (r *register) Regist(m mapping.ExampleMapping) {
1919
m["cmdexec_withcontext"] = WithContext
2020
m["cmdexec_pipe"] = Pipe
2121
m["cmdexec_multi_command_with_pipe"] = MultiCommandWithPipe
22+
m["cmdexec_env"] = WithEnv
2223
}

examples/basic/cmdexec/withenv.go

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package cmdexec
2+
3+
import (
4+
"errors"
5+
"os"
6+
"os/exec"
7+
"runtime"
8+
9+
"github.com/devlights/gomy/output"
10+
)
11+
12+
// WithEnv -- *exec.Cmd 実行時に追加の環境変数を指定するサンプルです.
13+
//
14+
// REFERENCES
15+
// - https://dev.to/tobychui/quick-notes-for-go-os-exec-3ejg
16+
func WithEnv() error {
17+
if runtime.GOOS == "windows" {
18+
return errors.New("this example cannot run on Windows, sorry")
19+
}
20+
21+
const (
22+
Shell = "/bin/bash"
23+
)
24+
25+
var (
26+
cmd *exec.Cmd
27+
out []byte
28+
err error
29+
)
30+
31+
//
32+
// 環境変数の追加なし
33+
//
34+
cmd = exec.Command(Shell, "-c", "env | grep LANG")
35+
36+
out, err = cmd.Output()
37+
if err != nil {
38+
return err
39+
}
40+
41+
output.Stdoutf("[no append]", "\n%s\n", out)
42+
output.StdoutHr()
43+
44+
//
45+
// 環境変数の追加あり
46+
//
47+
cmd = exec.Command(Shell, "-c", "env | grep LANG")
48+
cmd.Env = append(os.Environ(), "LANG2=Japanese")
49+
50+
out, err = cmd.Output()
51+
if err != nil {
52+
return err
53+
}
54+
55+
output.Stdoutf("[append ]", "\n%s\n", out)
56+
output.StdoutHr()
57+
58+
return nil
59+
}

0 commit comments

Comments
 (0)