File tree Expand file tree Collapse file tree 3 files changed +61
-0
lines changed
Expand file tree Collapse file tree 3 files changed +61
-0
lines changed Original file line number Diff line number Diff line change 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 実行時にワーキングディレクトリを指定するサンプルです|
Original file line number Diff line number Diff 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}
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments