如何在 Go 的单个 Shell 实例中顺序运行多个命令?
Nov 25, 2024 am 05:35 AM在同一个 Shell 中顺序运行多个命令:分析和解决方案
提供的 Go 代码旨在顺序执行多个命令,每个命令都在其自己独立的 shell 实例。但是,它遇到了第二个和第三个命令失败并显示可执行文件不存在的错误的问题。这是因为每个命令都在新的 shell 中执行,从而丢失了前面命令的上下文。
要解决此问题,需要在同一个 shell 实例中继续执行所有命令。这可以通过使用以下方法来实现:
// Run multiple commands in the same shell instance func runCommands(commands []string) error { // Create a pipe for controlling the shell's standard input and output reader, writer, err := os.Pipe() if err != nil { return err } defer reader.Close() defer writer.Close() // Start the shell command cmd := exec.Command("/bin/sh") cmd.Stdin = reader cmd.Stdout = writer // Start the command and wait for it to finish if err := cmd.Start(); err != nil { return err } if err := cmd.Wait(); err != nil { return err } // Write each command to the shell's standard input for _, command := range commands { if _, err := writer.Write([]byte(command + "\n")); err != nil { return err } } // Close the pipe to signal the end of input if err := writer.Close(); err != nil { return err } // Read the output from the shell command output, err := ioutil.ReadAll(reader) if err != nil { return err } // Return the output return nil }
登录后复制
此函数将一段命令作为输入,并在单个 shell 实例中按顺序执行它们。它将命令通过管道传输到 shell 的标准输入,然后读取其输出。
通过使用这种方法,后续命令将在与前面的命令相同的工作目录中执行,并且前面遇到的问题将得到解决.
以上是如何在 Go 的单个 Shell 实例中顺序运行多个命令?的详细内容。更多信息请关注PHP中文网其他相关文章!
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门文章
仓库:如何复兴队友
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
击败分裂小说需要多长时间?
3 周前
By DDD
Hello Kitty Island冒险:如何获得巨型种子
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 周前
By 尊渡假赌尊渡假赌尊渡假赌
公众号网页更新缓存难题:如何避免版本更新后旧缓存影响用户体验?
3 周前
By 王林

热门文章
仓库:如何复兴队友
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
击败分裂小说需要多长时间?
3 周前
By DDD
Hello Kitty Island冒险:如何获得巨型种子
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 周前
By 尊渡假赌尊渡假赌尊渡假赌
公众号网页更新缓存难题:如何避免版本更新后旧缓存影响用户体验?
3 周前
By 王林

热门文章标签

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)