Skip to content

Commit 69979a8

Browse files
committed
Add cmdexec/withdir.go
1 parent 5a72b6e commit 69979a8

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
@@ -11,3 +11,4 @@
1111
|pipe.go|cmdexec\_pipe|(*Cmd).StdinPipe,StdoutPipe,StderrPipeのサンプルです|
1212
|multi\_command\_with\_pipe.go|cmdexec\_multi\_command\_with\_pipe|複数の (*exec.Cmd) をパイプストリームで繋いで実行するサンプルです|
1313
|withenv.go|cmdexec\_env|*exec.Cmd 実行時に追加の環境変数を指定するサンプルです|
14+
|withdir.go|cmdexec\_dir|*exec.Cmd 実行時にワーキングディレクトリを指定するサンプルです|

examples/basic/cmdexec/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,5 @@ func (r *register) Regist(m mapping.ExampleMapping) {
2020
m["cmdexec_pipe"] = Pipe
2121
m["cmdexec_multi_command_with_pipe"] = MultiCommandWithPipe
2222
m["cmdexec_env"] = WithEnv
23+
m["cmdexec_dir"] = WithDir
2324
}

examples/basic/cmdexec/withdir.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+
// WithDir -- *exec.Cmd 実行時にワーキングディレクトリを指定するサンプルです.
13+
//
14+
// REFERENCES
15+
// - https://dev.to/tobychui/quick-notes-for-go-os-exec-3ejg
16+
func WithDir() 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+
output.Stdoutl("[cwd]", func() string { c, _ := os.Getwd(); return c }())
32+
33+
//
34+
// プロセス実行時のワーキングディレクトリの指定なし
35+
//
36+
cmd = exec.Command(Shell, "-c", "pwd")
37+
38+
out, err = cmd.Output()
39+
if err != nil {
40+
return err
41+
}
42+
43+
output.Stdoutf("[no dir]", "%s", out)
44+
45+
//
46+
// プロセス実行時のワーキングディレクトリの指定あり
47+
//
48+
cmd = exec.Command(Shell, "-c", "pwd")
49+
cmd.Dir = "/tmp"
50+
51+
out, err = cmd.Output()
52+
if err != nil {
53+
return err
54+
}
55+
56+
output.Stdoutf("[with dir]", "%s", out)
57+
58+
return nil
59+
}

0 commit comments

Comments
 (0)