【问题标题】:How to execute shell script inside go file? [closed]如何在 go 文件中执行 shell 脚本? [关闭]
【发布时间】:2021-05-05 10:55:34
【问题描述】:

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

go 文件除了执行 shell 脚本之外什么都没有做(它必须是一个 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,脚本会打印什么,尽管我提供了。我做错了什么?

【问题讨论】:

  • 我认为 bash 脚本希望您为其提供一个参数。您的代码显然没有。因此,shell 脚本打印出它的帮助信息并退出。换句话说:您需要将您提供给 GO 的参数也传递给 bash 调用!
  • 并注意:当给出的答案解决了您的问题时,请不要犹豫接受它(靠近答案投票数的复选标记图标)

标签: shell go


【解决方案1】:

此错误消息源自调用的 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 out of range 恐慌。

【讨论】:

  • 好吧,我确实做了你说的所有改变!但现在什么都没有执行!当我运行“go run myfile.go http://example.com”时,什么也没有发生!
  • 好的,非常感谢您的帮助。但我确实了解 bash 脚本!我认为这与 go 相关(因为我是该语言的新手)。我将再次查看 bash 脚本,看看我是否遗漏了什么。 :)
  • 有一个缺失的“}”,我相信它被错误地删除了。它以前对我很好,这就是为什么我认为它是 go 文件!但我确实了解 bash 脚本先生! :) 再次感谢您。
  • @Nadeen 欢迎您。是的,总是剖析问题是关键。在您通过另一个工具 Y 使用工具 X 之前,请确保 X 完全按照您的想法工作!
猜你喜欢
  • 2023-02-17
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 2013-04-08
  • 1970-01-01
  • 2016-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多