Environment Variables in Nim

Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables in Nim.

import os, strutils

proc main() =
  # To set a key/value pair, use putEnv. To get a
  # value for a key, use getEnv. This will return
  # an empty string if the key isn't present in the
  # environment.
  putEnv("FOO", "1")
  echo "FOO: ", getEnv("FOO")
  echo "BAR: ", getEnv("BAR")

  # Use envPairs to list all key/value pairs in the
  # environment. This returns a sequence of (string, string)
  # tuples. Here we print all the keys.
  echo ""
  for (key, _) in envPairs():
    echo key

main()

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is empty.

$ nim c -r environment_variables.nim
FOO: 1
BAR: 

The list of keys in the environment will depend on your particular machine.

TERM_PROGRAM
PATH
SHELL
...
FOO

If we set BAR in the environment first, the running program picks that value up.

$ BAR=2 nim c -r environment_variables.nim
FOO: 1
BAR: 2
...

In Nim, we use putEnv to set environment variables and getEnv to retrieve them. The envPairs iterator is used to list all environment variables. The strutils module is imported for string manipulation functions, although it’s not used in this specific example.

Note that Nim’s approach to environment variables is quite similar to other languages, making it straightforward to work with configuration data passed through the environment.