【发布时间】:2022-01-21 19:23:30
【问题描述】:
我在 golang 中使用 docker 的 sdk 来执行 docker exec 命令。
func (dn *dockerNode) execCommand(ctx context.Context, cmd []string) (*execResult, error) {
execId, err := dn.cl.ContainerExecCreate(ctx, dn.contId, types.ExecConfig{
AttachStderr: true,
AttachStdout: true,
Tty: true,
Cmd: cmd,
})
if err != nil {
return nil, fmt.Errorf(
"cannot create command \"%s\":\n %v",
strings.Join(cmd, " "),
err,
)
}
res, err := dn.InspectExecResp(ctx, execId.ID)
if err != nil {
return nil, fmt.Errorf(
"cannot execute command \"%s\":\n %v",
strings.Join(cmd[:], " "),
err,
)
}
if res.exitCode != 0 {
return &res, fmt.Errorf(
"command \"%s\" exit with code %d:\n %+v",
strings.Join(cmd[:], " "),
res.exitCode,
res)
}
return &res, nil
}
这个dn.execCommand 只适用于一些普通的docker exec foo bar 格式命令,但现在我想用它来运行相当于docker exec bash -c "cd mydir && ./my_shell.sh" 的东西。这是因为cd 命令仅适用于docker exec bash -c。我尝试通过
res, err = dn.execCommand(
ctx,
[]string{
"bash",
"-c",
"\"cd mydir && ./my_shell.sh\"",
},
)
但它给了我command "bash -c "cd mydir && ./my_shell.sh" " exit with code 127
我想知道如何修改原始函数以使其支持docker exec bash -c 用例。
【问题讨论】: