英文:
Record exit code from command
问题
我正在尝试在Go语言中运行以下代码来执行命令:
cmd := exec.Command(shell, `-c`, unsliced_string)
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Run()
变量shell
是从os.Getenv("$SHELL")
获取的,而变量unsliced_string
是从命令行传入的参数。
我需要在命令运行后获取其状态/错误代码。
所以,如果要运行的命令(来自命令行)是exit 100
,我需要保存一个变量,其中包含错误状态代码,即100。
总的来说,我需要一个变量来记录命令运行的错误代码。
我尝试使用.Error()
,但它返回的是exit status 100
,而不是只有100
。
作为最后的办法,我可以使用strings.ReplaceAll
或strings.Trim
。
英文:
I am trying to run a command within go with the following lines of code.
cmd := exec.Command(shell, `-c`, unsliced_string)
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Run()
the variable shell is gathered from os.Getenv("$SHELL")
and variable unsliced_string is the args fed from the command line.
I need the status/error code from the command after it runs.
So if the command being run (from the command) is exit 100
, i need a variable saved which retains the error status code, in this case 100
Overall, i need a variable which records the error code of the command run
I have tried using .Error() however it has exit status 100
instead of just 100
As a last resort I can just use strings.Replaceall or strings.Trim
答案1
得分: 3
当然,有两种方法:
cmd := exec.Command(shell, `-c`, unsliced_string)
err := cmd.Run()
if exitErr, ok := err.(*exec.ExitError); ok {
exitCode := exitErr.ExitCode()
fmt.Println(exitCode)
} else if err != nil {
// 另一种类型的错误发生了,应该在这里处理
// 例如:如果$SHELL没有指向可执行文件等...
}
cmd := exec.Command(shell, `-c`, unsliced_string)
_ := cmd.Run()
exitCode := cmd.ProcessState.ExitCode()
fmt.Println(exitCode)
我强烈建议使用第一种选项,这样你可以捕获所有的exec.ExitError
并按照你的需求处理它们。另外,如果命令尚未退出或由于其他错误而未运行底层命令,则cmd.ProcessState不会被填充,因此使用第一种选项更安全。
英文:
Sure, there are two ways:
cmd := exec.Command(shell, `-c`, unsliced_string)
err := cmd.Run()
if exitErr, ok := err.(*exec.ExitError); ok {
exitCode := exitErr.ExitCode()
fmt.Println(exitCode)
} else if err != nil {
// another type of error occurred, should handle it here
// eg: if $SHELL doesn't point to an executable, etc...
}
cmd := exec.Command(shell, `-c`, unsliced_string)
_ := cmd.Run()
exitCode := cmd.ProcessState.ExitCode()
fmt.Println(exitCode)
I would highly recommend using the first option, that way you can catch all exec.ExitError
's and handle them how you want. Also cmd.ProcessState is not populated if the command has not exited or if the underlying command is never run due to another error, so safer to use the first option.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论