-
Notifications
You must be signed in to change notification settings - Fork 0
/
withdir.go
76 lines (57 loc) · 1.33 KB
/
withdir.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package cmdexec
import (
"errors"
"os"
"os/exec"
"runtime"
"github.com/devlights/gomy/output"
)
// WithDir -- *exec.Cmd 実行時にワーキングディレクトリを指定するサンプルです.
//
// REFERENCES
// - https://dev.to/tobychui/quick-notes-for-go-os-exec-3ejg
func WithDir() error {
if runtime.GOOS == "windows" {
return errors.New("this example cannot run on Windows, sorry")
}
const (
Shell = "/bin/bash"
)
var (
cmd *exec.Cmd
out []byte
err error
)
output.Stdoutl("[cwd]", func() string { c, _ := os.Getwd(); return c }())
//
// プロセス実行時のワーキングディレクトリの指定なし
//
cmd = exec.Command(Shell, "-c", "pwd")
out, err = cmd.Output()
if err != nil {
return err
}
output.Stdoutf("[no dir]", "%s", out)
//
// プロセス実行時のワーキングディレクトリの指定あり
//
cmd = exec.Command(Shell, "-c", "pwd")
cmd.Dir = "/tmp"
out, err = cmd.Output()
if err != nil {
return err
}
output.Stdoutf("[with dir]", "%s", out)
return nil
/*
$ task
task: [build] go build .
task: [run] ./try-golang -onetime
ENTER EXAMPLE NAME: cmdexec_dir
[Name] "cmdexec_dir"
[cwd] /workspace/try-golang
[no dir] /workspace/try-golang
[with dir] /tmp
[Elapsed] 3.23569ms
*/
}