Golang os.Expand() and ExpandEnv() functions example

package os

Golang os.Expand() and ExpandEnv() functions usage example

 package main

 import (
 "fmt"
 "os"
 )

 func testGetenv(s string) string {
 switch s {
 case "*":
 return "all the args"
 case "#":
 return "NARGS"
 case "$":
 return "PID"
 case "1":
 return "ARGUMENT1"
 case "HOME":
 return "/usr/gopher"
 case "H":
 return "(Value of H)"
 case "home_1":
 return "/usr/foo"
 case "_":
 return "underscore"
 }
 return ""
 }

 func main() {

 str := os.Expand("$1", testGetenv)
 fmt.Println(str)

 str = os.Expand("$HOME", testGetenv)
 fmt.Println(str)

 // ----------------------------

 str = os.Expand("HOME", os.Getenv) // without $ is wrong way to use os.Expand function
 fmt.Println(str)

 str = os.Expand("$HOME", os.Getenv) // extract from environment
 fmt.Println(str)

 str = os.ExpandEnv("$HOME") // another way to extract from environment
 fmt.Println(str)

 }

Sample output :

ARGUMENT1

/usr/gopher

HOME

/root

/root

References :

http://golang.org/pkg/os/#Expand

http://golang.org/pkg/os/#ExpandEnv

Advertisement