如何将 Golang 变量传递给 Bash 脚本?

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

How do i pass a Golang variable to Bash Script?

问题

script.sh
>

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

想要运行这个 shell 脚本,从我的 .go 文件中获取变量 model_tag

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.Env = append(os.Environ(), fmt.Sprintf("model_tag=%s", mt))
	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))
}

在这里,mt 是从请求中接收到的头部信息,我需要在执行 shell 脚本之前将其传递给脚本。
如何在使用 go 文件执行 shell 脚本之前设置 model_tag = mt?

尝试直接设置 model_tag = mt,会抛出语法错误。

英文:

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

答案1

得分: 2

在执行运行 script.sh 的命令之前,执行以下操作:

os.Setenv("model_tag", mt)
英文:

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

os.Setenv("model_tag", mt)

答案2

得分: 0

尝试使用以下代码:

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

请注意,这是一段Go语言代码,用于执行Shell命令。

英文:

try with

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

huangapple
  • 本文由 发表于 2022年11月18日 17:51:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/74487779.html
匿名

发表评论

匿名网友

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

确定