Go 运行shell脚本

用Go调用shell脚本:

package main

import (
    "os/exec"
    "os"
    "fmt"
)

func main() {
    cmd, err := Script("test.sh")
    if err != nil {
        fmt.Printf("exec err:%v", err)
    }
    err = cmd.Run() //运行脚本
    if err != nil {
        fmt.Printf("shell run err:%v", err)
    }
}

// Script returns a command to execute a script through a shell.
func Script(script string) (*exec.Cmd, error) {
    shell := "/bin/sh"
    if other := os.Getenv("SHELL"); other != "" {
        shell = other
    }
    return exec.Command(shell, "-c", script), nil
}

你可能感兴趣的:(Go 运行shell脚本)