如何从 go 将变量值传递给 shell 脚本?

发布于 2025-01-16 02:42:25 字数 774 浏览 0 评论 0原文

shell.sh

#!/bin/bash
npx create-react-app <project-name> --template typescript

run.go

func runScript(genErr *error) {
    if *genErr != nil {
        return
    }

    cmd := exec.Command("/bin/sh", "-c", shell)
    *genErr = cmd.Run()
}

details.go

type npmLibCommand struct {
    ProjectName string
}

var npmLib npmLibCommand

func getNpmLibraryInput(genErr *error) {
    if *genErr != nil {
        return
    }
    npmLib.ProjectName = GetProjectName(genErr)
}

我想从 run.go 传递 projectName 变量shell.sh。如何使用 golang 来做到这一点?

我在 shell.sh 中使用了 $。它不起作用。

shell.sh

#!/bin/bash
npx create-react-app <project-name> --template typescript

run.go

func runScript(genErr *error) {
    if *genErr != nil {
        return
    }

    cmd := exec.Command("/bin/sh", "-c", shell)
    *genErr = cmd.Run()
}

details.go

type npmLibCommand struct {
    ProjectName string
}

var npmLib npmLibCommand

func getNpmLibraryInput(genErr *error) {
    if *genErr != nil {
        return
    }
    npmLib.ProjectName = GetProjectName(genErr)
}

I want to pass projectName variable from run.goto shell.sh. How to do this using golang?

I used $ in shell.sh. It didn't work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

茶色山野 2025-01-23 02:42:25

a.sh

echo $PassedName

ma​​in.go

package main

import (
    "os"
    "os/exec"
)

func main() {
    // run your shell script
    // don't forget to mention ./
    cmd := exec.Command("/bin/sh", "-c", "./a.sh")

    // whatever variable you want to pass append it to cmd.Env
    // it's format is of key=value
    cmd.Env = append(cmd.Env, "PassedName=hello")
    // set stdout and stderr appropriately as per your needs
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    cmd.Run() // run the cmd
}

a.sh

echo $PassedName

main.go

package main

import (
    "os"
    "os/exec"
)

func main() {
    // run your shell script
    // don't forget to mention ./
    cmd := exec.Command("/bin/sh", "-c", "./a.sh")

    // whatever variable you want to pass append it to cmd.Env
    // it's format is of key=value
    cmd.Env = append(cmd.Env, "PassedName=hello")
    // set stdout and stderr appropriately as per your needs
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    cmd.Run() // run the cmd
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文