Shell Function To Read Environment Variables

- 1 minute read

Here’s a simple shell function that reads specific environment variables from environment files:

#!/bin/bash

var() {
    VAR=$(grep $1 $2 | xargs)
    IFS="=" read -ra VAR <<< "$VAR"
    echo ${VAR[1]}
}

It requires two parameters.

  1. The name of the variable to read.

  2. The path to the environment file you’d like to read the variable from.

Link to this section Usage

Suppose you have a .env file with the following content:

FOO=BAR

If you want to read the value of FOO, you can invoke the var() function like this:

FOO=$(var FOO .env)
echo "$FOO"

And that will return the following output:

BAR

Pretty handy, right?

Link to this section Conclusion

I’ve found myself using this same little snippet over and over again.

It’s especially useful for keeping private data, such as API keys, safe from explicit reference within your public scripts.

Enjoy!