Is there a way to validate a .env file?

Viewed 4129

I'm getting errors when trying to parse a .env file I have, but I have no way of figuring out where it's erring out. Is there an easy way to lint/validate the file, online or otherwise?

Many thanks!

2 Answers

It depends on the syntax you are using. Looking at the Docker and NPM documentation, different tools seem to have a different scope on what they are able to parse.

I use a simple grep to validate if I have a <key>=<value> pattern, where key and value are non-empty. You can adapt the patterns to match your context, ensuring upper case keys for example.

#!/bin/bash

for envfile in $(find . -maxdepth 1 -type f -name '.env.*'); do 
    for line in $(cat ${envfile}); do
        # exclude comments
        if [[ "${line:0:1}" == "#" ]]; then
            continue
        fi

        match_line=$(echo ${line} | grep -E "^[A-Za-z0-9_].+=.+$")

        if [[ ${match_line} == "" ]]; then
            echo "Error in file: ${envfile}: line: ${line}"
        fi
    done
done

Alternatively, look at your language loadenv library to see if you can catch specific parsing exceptions, if available, to narrow down the specific line that causes the error.

Related