英文:
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.go
to 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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论