登录
首页 >  Golang >  Go问答

在Golang中如何运行Shell脚本文件?

来源:stackoverflow

时间:2024-02-16 16:45:23 459浏览 收藏

大家好,我们又见面了啊~本文《在Golang中如何运行Shell脚本文件?》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

我想在 golang 文件中运行 shell 脚本(大约 75 行)。

go文件除了执行shell脚本之外没有任何作用(它必须是一个go文件:))

我正在运行的代码是这样的: go 文件:

package main

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

func main() {
    out:= native()
    fmt.println(out)
}
func native() string {
    cmd, err := exec.command("/bin/bash", "./file.sh").output()

    if err != nil {
    fmt.printf("error %s", err)
    }
 
    output := string(cmd)
    return output
}

我使用 go run myfile.go http://example.com 运行它。

它开始执行,但停止了,我看到此错误消息:

Please specify a target.
                                                                             
Usage:
  ./file.sh http://domain.tld/                                              
  cat urls.txt | ./file.sh  

如果我没有提供 url(尽管我提供了),脚本就会打印出以下内容。我做错了什么?


正确答案


此错误消息源自被调用的 shell 脚本。您仅将参数 http://example.com 传递给 go 程序,而不进一步传递给 shell 脚本。

更改此代码

func native() string {
    cmd, err := exec.command("/bin/bash", "./file.sh").output()

    if err != nil {
    fmt.printf("error %s", err)
    }
 
    output := string(cmd)
    return output
}

func native(target string) string {
    cmd, err := exec.command("/bin/bash", "./file.sh", target).output()

    if err != nil {
    fmt.printf("error %s", err)
    }
 
    output := string(cmd)
    return output
}

将实际调用更改为

out:= Native(os.Args[1])

您必须再次导入“os”。

请记住,此处不对参数进行检查。当没有传入参数时,程序会出现 index 超出范围 的情况。

以上就是《在Golang中如何运行Shell脚本文件?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>