加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 22:29:14 所属栏目:安全 来源:网络整理
导读:我无法确定如何使用os / exec包运行多个命令.我已经控制了网络和stackoverflow,并没有发现任何适用于我的情况.这是我的来源: package mainimport ( _ "bufio" _ "bytes" _ "errors" "fmt" "log" "os" "os/exec" "path/filepath")func main() { ffmpegFolder
我无法确定如何使用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路径; ./配置;使
所以我需要按顺序运行每个命令并等待最后一个命令完成后再继续.使用我当前版本的代码,它目前说的是./configure:没有这样的文件或目录我认为这是因为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解释给定的命令.它还可以让你像cd一样执行shell内置函数.请注意,以安全的方式将用户数据替换为这些命令可能并非易事.

如果您只想在特定目录中运行命令,则可以在没有shell的情况下执行此操作.您可以设置当前工作目录以执行命令,如下所示:

config := exec.Command("./configure","--disable-yasm")
config.Dir = folderPath
build := exec.Command("make")
build.Dir = folderPath

……继续像往常一样.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读