Nim environment variables - read, set, delete, exists, and iterate examples?

This tutorial explains Environment variables in NIM.

How to read environment variable

The os module contains the getEnv procedure that returns the environment variable value for a given variable.

syntax: if the environment variable is not found, return the default value

proc getEnv(key: string; default = ""): string {.....}
import os
echo getEnv("HOME")

HOME is equivalent to $HOME in Linux(Unix) and %HOME% in Windows Another example

import os
echo getEnv("NIM_HOME","default")

It returns either value or default if not found.

use existsEnv to differentiate between actual and default value

proc existsEnv(key: string): bool {.....}

How to set environment variable in Nim

putEnv procedure to add environment variable with a value. OSError is thrown if an error occurs

proc putEnv(key, val: string) {.....}

Here is an example

import os
echo putEnv("production","true")
echo getEnv("production") # true

How to delete environment variable in Nim

delEnv procedure to delete a given environment variable and its value. OSError is thrown if an error occurred

proc delEnv(key: string) {.....}

Here is an example

import os
echo putEnv("production", "true")
echo getEnv("production") # true
echo delEnv("production")
echo getEnv("production") # false

How to check if an environment variable exists or not in Nim

existsEnv procedure to check given environment variable exists or not. OSError is thrown if an error occurred

proc existsEnv(key: string): bool {.....}

Here is an example

import os
echo putEnv("production","true")
echo getEnv("production") # true
echo delEnv("production")
echo getEnv("production","Does not exists") # Does not exists

How to iterate all Environment variables in Nim

The envPairs() procedure iterates each environment variable and returns a tuple. Tuple contains a key variable and its value. Syntax:

iterator envPairs(): tuple[key, value: string] {.....}

Here is an example

import os

for (key, value) in envPairs:
echo key , " = " ,value