如何从Go语言将变量值传递给Shell脚本?

huangapple go评论88阅读模式
英文:

How to pass variable value to shell script from go?

问题

shell.sh

#!/bin/bash
npx create-react-app $projectName --template typescript

run.go

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

	cmd := exec.Command("/bin/sh", "-c", "projectName="+projectName+" shell.sh")
	*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)
}

我想将 projectName 变量从 run.go 传递到 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.

答案1

得分: 1

a.sh

echo $PassedName

main.go

package main

import (
	"os"
	"os/exec"
)

func main() {
	// 运行你的shell脚本
	// 不要忘记提及./
	cmd := exec.Command("/bin/sh", "-c", "./a.sh")

	// 无论你想传递的变量是什么,都将其附加到cmd.Env中
	// 它的格式是key=value
	cmd.Env = append(cmd.Env, "PassedName=hello")
	// 根据需要适当设置stdout和stderr
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Run() // 运行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
}

huangapple
  • 本文由 发表于 2022年3月23日 00:16:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/71575436.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定