github.com/markusbkk/elvish@v0.0.0-20231204143114-91dc52438621/pkg/eval/builtin_fn_env.go (about) 1 package eval 2 3 import ( 4 "errors" 5 "os" 6 ) 7 8 // ErrNonExistentEnvVar is raised by the get-env command when the environment 9 // variable does not exist. 10 var ErrNonExistentEnvVar = errors.New("non-existent environment variable") 11 12 //elvdoc:fn set-env 13 // 14 // ```elvish 15 // set-env $name $value 16 // ``` 17 // 18 // Sets an environment variable to the given value. Example: 19 // 20 // ```elvish-transcript 21 // ~> set-env X foobar 22 // ~> put $E:X 23 // ▶ foobar 24 // ``` 25 // 26 // @cf get-env has-env unset-env 27 28 //elvdoc:fn unset-env 29 // 30 // ```elvish 31 // unset-env $name 32 // ``` 33 // 34 // Unset an environment variable. Example: 35 // 36 // ```elvish-transcript 37 // ~> set E:X = foo 38 // ~> unset-env X 39 // ~> has-env X 40 // ▶ $false 41 // ~> put $E:X 42 // ▶ '' 43 // ``` 44 // 45 // @cf has-env get-env set-env 46 47 func init() { 48 addBuiltinFns(map[string]interface{}{ 49 "has-env": hasEnv, 50 "get-env": getEnv, 51 "set-env": os.Setenv, 52 "unset-env": os.Unsetenv, 53 }) 54 } 55 56 //elvdoc:fn has-env 57 // 58 // ```elvish 59 // has-env $name 60 // ``` 61 // 62 // Test whether an environment variable exists. Examples: 63 // 64 // ```elvish-transcript 65 // ~> has-env PATH 66 // ▶ $true 67 // ~> has-env NO_SUCH_ENV 68 // ▶ $false 69 // ``` 70 // 71 // @cf get-env set-env unset-env 72 73 func hasEnv(key string) bool { 74 _, ok := os.LookupEnv(key) 75 return ok 76 } 77 78 //elvdoc:fn get-env 79 // 80 // ```elvish 81 // get-env $name 82 // ``` 83 // 84 // Gets the value of an environment variable. Throws an exception if the 85 // environment variable does not exist. Examples: 86 // 87 // ```elvish-transcript 88 // ~> get-env LANG 89 // ▶ zh_CN.UTF-8 90 // ~> get-env NO_SUCH_ENV 91 // Exception: non-existent environment variable 92 // [tty], line 1: get-env NO_SUCH_ENV 93 // ``` 94 // 95 // @cf has-env set-env unset-env 96 97 func getEnv(key string) (string, error) { 98 value, ok := os.LookupEnv(key) 99 if !ok { 100 return "", ErrNonExistentEnvVar 101 } 102 return value, nil 103 }