在同一shell golang中运行多个Exec命令

我在弄清楚如何使用os / exec包运行多个命令时遇到了麻烦。我已经摸索了网络和stackoverflow,还没有找到任何适合我的案例。这是我的资料来源:

package main

import (

_ "bufio"

_ "bytes"

_ "errors"

"fmt"

"log"

"os"

"os/exec"

"path/filepath"

)

func main() {

ffmpegFolderName := "ffmpeg-2.8.4"

path, err := filepath.Abs("")

if err != nil {

fmt.Println("Error locating absulte file paths")

os.Exit(1)

}

folderPath := filepath.Join(path, ffmpegFolderName)

_, err2 := folderExists(folderPath)

if err2 != nil {

fmt.Println("The folder: %s either does not exist or is not in the same directory as make.go", folderPath)

os.Exit(1)

}

cd := exec.Command("cd", folderPath)

config := exec.Command("./configure", "--disable-yasm")

build := exec.Command("make")

cd_err := cd.Start()

if cd_err != nil {

log.Fatal(cd_err)

}

log.Printf("Waiting for command to finish...")

cd_err = cd.Wait()

log.Printf("Command finished with error: %v", cd_err)

start_err := config.Start()

if start_err != nil {

log.Fatal(start_err)

}

log.Printf("Waiting for command to finish...")

start_err = config.Wait()

log.Printf("Command finished with error: %v", start_err)

build_err := build.Start()

if build_err != nil {

log.Fatal(build_err)

}

log.Printf("Waiting for command to finish...")

build_err = build.Wait()

log.Printf("Command finished with error: %v", build_err)

}

func folderExists(path string) (bool, error) {

_, err := os.Stat(path)

if err == nil {

return true, nil

}

if os.IsNotExist(err) {

return false, nil

}

return true, err

}

我想要命令,就像从终端一样。 cd path; ./configure; make

因此,我需要依次运行每个命令,并等待最后一个命令完成后再继续。在当前版本的代码中,当前./configure: no such file or

directory假设是因为执行cd path并在新的shell中执行了./configure,而不是与上一个命令位于同一目录中。有任何想法吗?

我通过更改工作目录然后执行./configure和make命令解决了该问题

err = os.Chdir(folderPath)

if err != nil {

fmt.Println("File Path Could not be changed")

os.Exit(1)

}

现在我还是很好奇,是否有办法在同一个外壳中执行命令。

回答:

如果要在单个shell实例中运行多个命令,则需要使用以下命令来调用shell:

cmd := exec.Command("/bin/sh", "-c", "command1; command2; command3; ...")

err := cmd.Run()

这将使外壳解释给定的命令。它还可以让您执行像这样的shell内置程序cd。请注意,以安全的方式将用户数据替换为这些命令并非易事。

相反,如果您只想在特定目录中运行命令,则可以在不使用Shell的情况下执行该操作。您可以将当前工作目录设置为执行命令,如下所示:

config := exec.Command("./configure", "--disable-yasm")

config.Dir = folderPath

build := exec.Command("make")

build.Dir = folderPath

…并像以前一样继续。

以上是 在同一shell golang中运行多个Exec命令 的全部内容, 来源链接: utcz.com/qa/416699.html

回到顶部