Unable to obtain the correct exit code for executing the command
faith01238 opened this issue · 3 comments
`liumou@liumou-PC:/media/liumou/Software/DATA/git/GoLang/dmeo$ cat exit.go
package main
import (
"gitee.com/liumou_site/logger"
"github.com/bitfield/script"
)
func main() {
cmd := script.Exec("lw")
res, _ := cmd.String()
code := cmd.ExitStatus()
logger.Debug("退出代码", code)
logger.Debug("输出: ", res)
}
liumou@liumou-PC:/media/liumou/Software/DATA/git/GoLang/dmeo$ go run exit.go
2022-11-29 21:51:04 [DEBG] [exit.go:12] 退出代码 0
2022-11-29 21:51:04 [DEBG] [exit.go:13] 输出: exec: "lw": executable file not found in $PATH
liumou@liumou-PC:/media/liumou/Software/DATA/git/GoLang/dmeo$ lw
bash: lw:未找到命令
liumou@liumou-PC:/media/liumou/Software/DATA/git/GoLang/dmeo$ echo $?
127
liumou@liumou-PC:/media/liumou/Software/DATA/git/GoLang/dmeo$ `
Using this method, you can obtain the correct
Go执行系统命令并获取退出代码
There's a couple of things going on here. First, ExitStatus returns the exit status of any command successfully run by Exec. If the command can't be run, because it doesn't exist (as in this example), it has no exit status, and so we wouldn't expect ExitStatus to return anything useful.
Try, for example:
cmd := script.Exec("ls bogus")
res, _ := cmd.String()
code := cmd.ExitStatus()https://go.dev/play/p/YvInbJGMiPR
This sets code to 1, as you'd expect.
Secondly, because the command lw doesn't exist, Exec encounters an error, which is then set on the pipe. Unfortunately, you've ignored this error value where it's returned by String. If you check the error, you'll find it's what you expect:
cmd := script.Exec("lw")
res, err := cmd.String()
if err != nil {
logger.Debug("錯誤", err)
logger.Debug("输出: ", res)
}I see. Thanks for your guidance. Because I am used to judging the execution results with exit codes, I have ignored the error types