Home > Software design >  How do i pass a Golang variable to Bash Script?
How do i pass a Golang variable to Bash Script?

Time:11-19

script.sh

#!/bin/sh
dbt run --select $model_tag --profiles-dir .

Want to run this shell script that takes the Variable model_tag from my .go file

invoke.go

package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
    "os/exec"
)

func handler(w http.ResponseWriter, r *http.Request) {
    log.Print("helloworld: received a request")
    mt := r.Header.Get("Model-Tag")

    cmd := exec.CommandContext(r.Context(), "/bin/sh","script.sh")
    cmd.Stderr = os.Stderr
    out, err := cmd.Output()
    if err != nil {
        w.WriteHeader(500)
    }
    w.Write(out)
}

func main() {
    log.Print("helloworld: starting server...")

    http.HandleFunc("/", handler)

    port := os.Getenv("PORT")
    if port == "" {
        port = "8080"
    }

    log.Printf("helloworld: listening on %s", port)
    log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}

Here, mt is the header being received from a request, that i need to pass to the shell script before execution? How do i set model_tag = mt before executing the shell script using the go file?

Tried setting model_tag = mt directly, throws a syntax error

CodePudding user response:

Before executing your cmd which runs script.sh, do a

os.Setenv("model_tag", mt)

CodePudding user response:

try with

    cmd := exec.CommandContext(r.Context(), "/bin/sh",fmt.Sprintf("model_tag=%s script.sh",mt))

  • Related