github.com/cilki/sh@v2.6.4+incompatible/shell/example_test.go (about) 1 // Copyright (c) 2018, Daniel Martà <mvdan@mvdan.cc> 2 // See LICENSE for licensing information 3 4 package shell_test 5 6 import ( 7 "context" 8 "fmt" 9 "io/ioutil" 10 "os" 11 12 "mvdan.cc/sh/shell" 13 ) 14 15 func ExampleExpand() { 16 env := func(name string) string { 17 switch name { 18 case "HOME": 19 return "/home/user" 20 } 21 return "" // leave the rest unset 22 } 23 out, _ := shell.Expand("No place like $HOME", env) 24 fmt.Println(out) 25 26 out, _ = shell.Expand("Some vars are ${missing:-awesome}", env) 27 fmt.Println(out) 28 29 out, _ = shell.Expand("Math is fun! $((12 * 34))", nil) 30 fmt.Println(out) 31 // Output: 32 // No place like /home/user 33 // Some vars are awesome 34 // Math is fun! 408 35 } 36 37 func ExampleFields() { 38 env := func(name string) string { 39 switch name { 40 case "foo": 41 return "bar baz" 42 } 43 return "" // leave the rest unset 44 } 45 out, _ := shell.Fields(`"many quoted" ' strings '`, env) 46 fmt.Printf("%#v\n", out) 47 48 out, _ = shell.Fields("unquoted $foo", env) 49 fmt.Printf("%#v\n", out) 50 51 out, _ = shell.Fields(`quoted "$foo"`, env) 52 fmt.Printf("%#v\n", out) 53 // Output: 54 // []string{"many quoted", " strings "} 55 // []string{"unquoted", "bar", "baz"} 56 // []string{"quoted", "bar baz"} 57 } 58 59 func ExampleSourceFile() { 60 src := ` 61 foo=abc 62 foo+=012 63 if true; then 64 bar=$(echo example_*.go) 65 fi 66 ` 67 ioutil.WriteFile("f.sh", []byte(src), 0666) 68 defer os.Remove("f.sh") 69 vars, err := shell.SourceFile(context.TODO(), "f.sh") 70 if err != nil { 71 return 72 } 73 fmt.Println(len(vars)) 74 fmt.Println("foo", vars["foo"]) 75 fmt.Println("bar", vars["bar"]) 76 // Output: 77 // 2 78 // foo abc012 79 // bar example_test.go 80 }