使用Golang 模板、Switch 和ForEach 產生Bash 腳本
挑戰
挑戰挑戰
<code class="go">package main import ( "log" "text/template" "gopkg.in/yaml.v2" "os" ) type File struct { TypeVersion string `yaml:"_type-version"` Dependency []Dependency `yaml:"dependency"` } type Dependency struct { Name string `yaml:"name"` Type string `yaml:"type"` CWD string `yaml:"cwd"` Install map[string]string `yaml:"install"` } var data = ` _type-version: "1.0.0" dependency: - name: ui type: runner cwd: /ui install: - name: api - name: ui2 type: runner2 cwd: /ui2 install: - name: api2 ` func main() { f := File{} err := yaml.Unmarshal([]byte(data), &f) if err != nil { log.Fatalf("error: %v", err) } const t = ` #!/bin/bash {{range .Dependency}} echo "type is {{.Type}}" {{switch .Type}} case "runner": echo "running command for runner" case "runner2": echo "running command for runner2" default: echo "unknown type" {{end}} {{end}} ` tt := template.Must(template.New("").Parse(t)) err = tt.Execute(os.Stdout, f) if err != nil { log.Println("executing template:", err) } }</code>
挑戰
要實現這一點,我們可以使用Go 模板,提供了一種從結構化資料產生文字檔案的便捷方法。這是使用具有switch 和ForEach 的範本的解決方案:
說明
#!/bin/bash type is runner running command for runner type is runner2 running command for runner2
以上是如何使用 Golang 範本、switch 語句和 ForEach 迴圈根據依賴類型產生具有特定命令的 Bash 腳本?的詳細內容。更多資訊請關注PHP中文網其他相關文章!