How to pass variable value to shell script from go?

1.1k Views Asked by At

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

There are 1 best solutions below

0
On

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
}