ADVERTISEMENT
ADVERTISEMENT

Golang os.Getenv() Function with Examples

Golang | os.Getenv() Function: Here, we are going to learn about the Getenv() function of the os package with its usages, syntax, and examples.
Submitted by IncludeHelp, on November 18, 2021

os.Getenv()

In the Go language, the os package provides a platform-independent interface to operating system (Unix-like) functionality. The Getenv() function is an inbuilt function of the os package, it is used to get the value of the environment variable specified by the key. It returns the value, which will be empty if the variable is not present.

It accepts one parameter (key string) and returns a string containing the value of the given environment variable, it may also be empty if the variable is not present.

Syntax:

func Getenv(key string) string

Parameter(s):

  • key - Environment variable whose value is to be found.

Return Value:

The return type of the os.Getenv() function is a string, it returns the value, which will be empty if the variable is not present.

Example 1:

// Golang program to demonstrate the
// example of Getenv() function

package main

import (
	"fmt"
	"os"
)

func main() {
	// Getting & printing the values of
	// PATH, HOSTNAME and HOME
	fmt.Println("PATH:", os.Getenv("PATH"))
	fmt.Println("HOSTNAME:", os.Getenv("HOSTNAME"))
	fmt.Println("HOME:", os.Getenv("HOME"))
}

Output:

PATH: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME: ef1235acfac8
HOME: /root

Example 2:

// Golang program to demonstrate the
// example of Getenv() function

package main

import (
	"fmt"
	"os"
)

func main() {
	// Setting the custom variables/fields
	os.Setenv("NAME", "Alvin")
	os.Setenv("EXAMPLE_PATH", "/root/Alvin/Examples")

	// Getting & printing the values of
	// NAME, and EXAMPLE_PATH
	fmt.Println("NAME:", os.Getenv("NAME"))
	fmt.Println("EXAMPLE_PATH:", os.Getenv("EXAMPLE_PATH"))
}

Output:

NAME: Alvin
EXAMPLE_PATH: /root/Alvin/Examples

Golang os Package »


ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.