Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Check if a environment variable is set in Go (Golang)

Posted on February 23, 2020February 23, 2020 by admin

os.LookupEnv function can be used to check whether a particular environment variable is set or not. It returns a bool which is true if the given env variable set otherwise false. Let’s see a working code:

package main

import (
    "fmt"
    "log"
    "os"
)

func main() {
    //Set env a to b
    err := os.Setenv("a", "x")
    if err != nil {
        log.Fatal(err)
    }

    val, present := os.LookupEnv("a")
    fmt.Printf("a env variable present: %t\n", present)
    fmt.Println(val)

    val, present = os.LookupEnv("b")
    fmt.Printf("b env variable present: %t\n", present)
}

Output:

a env variable present: true
x
b env variable present: false
  • env
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme