我无法确定如何使用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路径执行并且在新的shell ./configure中执行,而不是与前一个命令位于同一目录中.有任何想法吗?
更新我通过更改工作目录然后执行./configure和make命令解决了这个问题
err = os.Chdir(folderPath) if err != nil { fmt.Println("File Path Could not be changed") os.Exit(1) }
现在我仍然很想知道是否有办法在同一个shell中执行命令.
如果要在单个shell实例中运行多个命令,则需要使用以下内容调用shell:
cmd := exec.Command("/bin/sh", "-c", "command1; command2; command3; ...") err := cmd.Run()
这将使shell解释给定的命令.它还可以让你像shell一样执行shell内置函数cd
.请注意,以安全的方式将用户数据替换为这些命令可能并非易事.
如果您只想在特定目录中运行命令,则可以在没有shell的情况下执行此操作.您可以设置当前工作目录以执行命令,如下所示:
config := exec.Command("./configure", "--disable-yasm") config.Dir = folderPath build := exec.Command("make") build.Dir = folderPath
......继续像往常一样.