Skip to content

Commit d179472

Browse files
committed
Set exit-code when non-zero
Signed-off-by: Alex Ellis (OpenFaaS Ltd) <alexellis2@gmail.com>
1 parent f6e2331 commit d179472

File tree

3 files changed

+43
-8
lines changed

3 files changed

+43
-8
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
/go-execute
2+
main.go

README.md

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,31 +8,54 @@ A simple wrapper for Go's command execution packages.
88

99
See Godoc [github.com/alexellis/go-execute](https://godoc.org/github.com/alexellis/go-execute)
1010

11-
## Example
11+
## Example with "shell" and exit-code 0
1212

1313
```golang
1414
package main
1515

1616
import (
1717
"fmt"
18-
"os"
1918

2019
execute "github.com/alexellis/go-execute/pkg/v1"
2120
)
2221

2322
func main() {
2423
ls := execute.ExecTask{
2524
Command: "ls",
26-
Args: []string{"-la"},
27-
Cwd: os.Getenv("HOME"),
25+
Args: []string{"-l"},
2826
Shell: true,
2927
}
3028
res, err := ls.Execute()
3129
if err != nil {
3230
panic(err)
3331
}
3432

35-
fmt.Println(res.Stdout, res.Stderr)
33+
fmt.Printf("stdout: %q, stderr: %q, exit-code: %d\n", res.Stdout, res.Stderr, res.ExitCode)
34+
}
35+
```
36+
37+
## Example with "shell" and exit-code 1
38+
39+
```golang
40+
package main
41+
42+
import (
43+
"fmt"
44+
45+
execute "github.com/alexellis/go-execute/pkg/v1"
46+
)
47+
48+
func main() {
49+
ls := execute.ExecTask{
50+
Command: "exit 1",
51+
Shell: true,
52+
}
53+
res, err := ls.Execute()
54+
if err != nil {
55+
panic(err)
56+
}
57+
58+
fmt.Printf("stdout: %q, stderr: %q, exit-code: %d\n", res.Stdout, res.Stderr, res.ExitCode)
3659
}
3760
```
3861

pkg/v1/exec.go

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,9 @@ func (et ExecTask) Execute() (ExecResult, error) {
4242
} else {
4343
script := strings.Join(et.Args, " ")
4444
args = append([]string{"-c"}, fmt.Sprintf("%s %s", et.Command, script))
45+
4546
}
46-
fmt.Println(args)
47+
4748
cmd = exec.Command("/bin/bash", args...)
4849
} else {
4950
if strings.Index(et.Command, " ") > 0 {
@@ -95,8 +96,18 @@ func (et ExecTask) Execute() (ExecResult, error) {
9596

9697
fmt.Println("res: " + string(stdoutBytes))
9798

99+
exitCode := 0
100+
execErr := cmd.Wait()
101+
if execErr != nil {
102+
if exitError, ok := execErr.(*exec.ExitError); ok {
103+
104+
exitCode = exitError.ExitCode()
105+
}
106+
}
107+
98108
return ExecResult{
99-
Stdout: string(stdoutBytes),
100-
Stderr: string(stderrBytes),
109+
Stdout: string(stdoutBytes),
110+
Stderr: string(stderrBytes),
111+
ExitCode: exitCode,
101112
}, nil
102113
}

0 commit comments

Comments
 (0)